Running a cron job with CodeIgniter - codeigniter

I need to run a cron job on a file using CodeIgniter but CodeIgniter won't let me run a file directly. i.e.
I can run the controller in the browser with:
api.example.com/index.php/cron
My hosting only lets me run PHP files and I can't do it via the command line because it won't let me run wget or curl.
How can I make CodeIgniter run a file like below:
api.example.com/index.php/application/controller/cron.php
I can call that file with my hosting.
Updated
Thought i would just update none of the options worked for me i ended up changing hosting and doing the following.
http://devsforrest.com/116/setup-a-cronjob-to-run-every-5-minute-on-media-temple

Not sure if this is what you're looking for, or if I'm answering you wrong, but the way I run my CRON jobs with CodeIgniter is simply doing this as the cron:
php /path/to/index.php controller function
Then in the controller I have this at the top of it
if( PHP_SAPI != 'cli') exit('My Custom Error Message');

Uset wget command along with your url to run cron in codeigniter file in your case it should be:
wget api.example.com/index.php/controller/function
and be careful do not use path of file use the url which invokes your function.

class Cron extends CI_Controller {
function index($dummy) {
// Crony command
}
}
Line: api.example.com/index.php/cron/index/dummy.php
Basicly given example uses the 3rd uri segment to pass a value ending on .php that you don't use.
Or else you can use good ol' Routing

Use .htaccess to append .php to the requested URL, i did not test the code below, but i hope it helps.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php [R=301]

Use CURL and call your cronjob by URL. If CURL is enabled in your hosting that will be a good choice.
Create a PHP file name it cronjob.php in the root folder of your website and add the following script in a file.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.mysite.com/index.php/controller/method");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
?>
Now in the cronjob call the php file cronjob.php and it should work.

simply
/usr/local/bin/php /home/cpanel_username/public_html/sub_folder/index.php param1 param2 optional_param3 optional_param3
Here
cpanel_username - username of your domain cpanel,
sub_folder(optional) - if your web application is any folder
Param(parameters) - refers to controller and their methods(functions)

Codeigniter API Cronjob for godaddy hosting
CodeIgniter cron job API based daily 10 o clock
0 10 * * * /usr/local/bin/php public_html/folder_name/index.php controller_name funcation_name
For Me Working Fine

Related

laravel 4 on shared hosting: PAGE NOT FOUND

Due to a client issue i have to put a laravel 4 application on shared hosting service.But i followed this process at [laravelio]which includes.
Place the files of the laravel public folder i.e. css, img, js etc; into public_html folder (don't dump public folder instead dump the files and folders in it).
Put all the remaining folders & files into another folder, say 'laravelcore' and place the laravelcore folder in the root (/home5/username/)
Open index.php in the public_html folder and replace the following lines as mentioned
require DIR.'/../bootstrap/autoload.php';
require __DIR__.'/../laravelcore/bootstrap/autoload.php';
$app = require_once DIR.'/../bootstrap/start.php';
$app = require_once __DIR__.'/../laravelcore/bootstrap/start.php';
Open paths.php file in laravelcore/bootstrap and replace the following line
'public' => DIR.'/../public',
'public' => __DIR__.'/../../public_html',
which is suppose to work but when i visit the url i get this : The requested URL /login was not found on this server.please what may be the problem as i dont get it.may be its about configuring the .htacces file.
Any help would be appriciated.Thanks
website is at :benin1897.com
i just discovered that there is no .htaccess file in th public_html folder.could that be the problem...
here is my file tree
(/home/benincom)
etc
logs
mail
oysg
app
bootstrap
vendor
publicftp
public_html
css
js
error_log
readme
pakage.json
robots.txt
tmp
NOW AM LOGGED ON BUT LARAVEL THROWS ME ERROR
/ / |-------------------------------------------------------------------------- | Register The Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader | for our application. We just need to utilize it! We'll require it | into the script here so that we do not have to worry about the | loading of any our classes "manually". Feels great to relax. | / require DIR.'/../oysg/bootstrap/autoload.php'; / |-------------------------------------------------------------------------- | Turn On The Lights |-------------------------------------------------------------------------- | | We need to illuminate PHP development, so let's turn on the lights. | This bootstraps the framework and gets it ready for use, then it | will load up this application so that we can run it and send | the responses back to the browser and delight these users. | / $app = require_once DIR.'/../oysg/bootstrap/start.php'; / |-------------------------------------------------------------------------- | Run The Application |-------------------------------------------------------------------------- | | Once we have the application, we can simply call the run method, | which will execute the request and send the response back to | the client's browser allowing them to enjoy the creative | and wonderful application we have whipped up for them. | */ $app->run();
Do you've got the route for login handeld in your /app/routes.php like this?
Route::get('/login', 'LoginController#login');
Or if you don't use Controllers ( Which isn't an good idea, but for quick / dirty testing... )
Route::get('/login', function(){
echo "Now we're going to login on this awesome website!!!";
});
More about the Laravel Routes
Edit 1
The Controller file ( /app/controllers/LoginController.php ):
<?php
class LoginController extends BaseController {
public function login() {
echo "Now we are going to login in this awesome website!!!";
// return View::make('pages/overig/login');
}
}
You stated that there isn't an .htaccess file in you public folder. There should be one.
Create the file and insert this content and try it again:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
It sounds like the .htaccess file is not configured properly so you are not getting the 'pretty URLs'. Try copying the example file from here to your .htaccess http://laravel.com/docs/4.2/installation#pretty-urls.
In the meantime you should be able to access your application by prepending index.php. For instance /login wasn't working for you, but if you try /index.php/login it will work

cronjob in codeigniter using cpanel

My website hosting server is hostmonster.com.
My application uses codeigniter framework.
I have a code which sends emails to my users and I want to make it automatic.
I have used the cpanel of the hosting service and I tried to give the command as
php -q www.mysite.com/admin admin sendDailyEmail
my controller is admin and the method is sendDailyEmail and the controller is present inside the application/controllers/admin folder.
I have also set a reminder email to me whenever the cronjob is run.
The email subject reads
Cron php -q /home1/username/public_html/admin admin sendDailyEmail
and the body says
No input file specified
Where do I go wrong.
I have never run cronjobs and this is my first time.
I am no good in giving command line instuctions too.
My admin sendDailyEmail code is as follows
function sendDailyEmail() {
$data = $this->admin_model->getDailyData();
foreach ($data as $u) {
if($u->Daily){
//if(!$u->Amount){
if ($u->Email=='myemail#gmail.com') {
$user['user_data']['FirstName'] = $u->FirstName;
$user['user_data']['LastName'] = $u->LastName;
$user['user_data']['Id']=$u->Id;
$this->email->clear();
$this->email->to($u->Email);
$this->email->from('alerts#mysite.com', 'MySite');
$this->email->subject("My Subject");
$msg = $this->load->view('emails/daily_view', $user, true);
$this->email->message($msg);
if ($this->email->send())
$data['message'] = "Daily Emails has been sent successfully";
else
$data['message'] = "Daily Emails Sending Failed";
}
}
}
$data['main_content']['next_view'] = 'admin_home_view';
$this->load->view('includes/admin_template', $data);
}
You can use wget and set the time for whatever you like:
wget http://www.mysite.com/admin/sendDailyEmail
You can also use curl:
curl --silent http://www.mysite.com/admin/sendDailyEmail
For CodeIgniter 2.2.0
You can try this:
php-cli /home/username/public_html/index.php controller method
or at your case
php-cli /home/username/public_html/index.php admin sendDailyEmail
It works fine with me..
Cheers!
Codeigniter sets up command line differently for running crons, etc.
Read:
http://www.codeigniter.com/user_guide/general/cli.html
So you should run:
php index.php admin admin sendDailyEmail
(that may need adjusted; based on your code above)
Have a look at an article I just wrote that goes a little deeper into it all:
http://codebyjeff.com/blog/2013/10/setting-environment-vars-for-codeigniter-commandline
i have facing same issue while, but following work for me
wget http://www.yoursite.com/controller/function

Wordpress localhost doesn't show front-end

Can't see the front end of my wordpress localhost.
The process I've done:
1. I installed wordpress locally with BitNami on Mac OX.
2. imported an existing data base to the phpmyadmin.
3. changed the wp-config file to support the local host database.
4. added these two lines
define('WP_HOME','http://localhost/wordpress');
define('WP_SITEURL','http://localhost/wordpress');
5. logged in to my wp-admin.
Now I can see the site's WP-ADMIN and do things in it BUT I cannot view the front end.
whenever I try i get:
can't establish a connection to the server at 127.0.0.1.
or if i try to view a post i get
"The requested URL /site/2013/02/13/idho_global/ was not found on this server."
If I'm trying to preview a draft I see it the way it should appear.
any help?
Check the database via phpmydmin and change the url if you didn't do it.
In the wp_options check if siteurl & home are set to localhost
Update : you should have a look to the 'Moving Wordpress page' https://codex.wordpress.org/Moving_WordPress
It explains very well ho to change permalinks and things to do after moving a Wordpress.
If your permalinks don't works, check if you have a .htaccess in the root directory. The content should be :
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
You need to update the database urls. Wordpress hardcodes them. Run the sql below replacing "old-url.com/wordpress" and "new-url.com/wordpress" with your urls
UPDATE wp_posts SET guid = REPLACE(guid, 'old-url.com/wordpress', 'new-url.com/wordpress');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'old-url.com/wordpress', 'new-url.com/wordpress');
UPDATE wp_options SET option_value = REPLACE(option_value, 'old-url.com/wordpress', 'new-url.com/wordpress');

CodeIgniter Cron Job on Shared Hosting?

I am trying to learn how to do my first cron job using CodeIgniter. In the past, it seemed the only way to do this with CI was to use the wget command instead of php.
The CodeIgniter User Guide, however, says that now you can do this from the command line, for example by running:
$ cd /path/to/project;
$ php index.php controller method
This works great using Terminal on my local setup. But when I use a similar command in the cron section of cPanel on my shared hosting, the task just returns the contents of index.php.
I'm not entirely sure what cPanel does with this command, so unsure as to whether it's using the command line at all.
Could someone explain how I might be able to set up a cron job on shared hosting using CodeIgniter please?
Here is the example code from the CodeIgniter user guide:
tools.php
public function message($to = 'World')
{
echo "Hello {$to}!".PHP_EOL;
}
}
?>
It's going to depend on your host. Cron jobs could really screw stuff up if you're not careful, so a lot of shared hosts don't allow it. You probably need to be on some virtual container (like a VPS, virtuozo, etc.) to do this. This isn't a CodeIgniter issue, but a hosting provider issue. Call them first.
We worked around this exact issue as follows:
Set up a normal php file that is scheduled by cron. Nothing to do with codeigniter yet
Inside it, you can make an fsocket or curl request to perform your regular CodeIgniter call as you do from the web.
Here's an example (say, cron.php)
#!/usr/local/bin/php.cli
<?php
DEFINE('CRON_CALL_URL','https://my_server/'); //
DEFINE('CRON_HTTPS_PORT', 443); // port to use during fsocket connetion
DEFINE('CRON_SSL_PREFIX', 'ssl://'); // prefix to be used on the url when using ssl
$current_time = now();
$md5_hash = md5('somevalue'.$current_time);
$url = CRON_CALL_URL.'MYCTRL/MYMETHOD';
$parts=parse_url($url);
//
$parts['query']='md5_hash='.$md5_hash.'&time='.$current_time;
$fp = fsockopen(CRON_SSL_PREFIX.$parts['host'],
isset($parts['port'])?$parts['port']:CRON_HTTPS_PORT,
$errno, $errstr, 30);
if (!$fp) {
} else {
if (!array_key_exists('query', $parts)) $parts['query'] = null;
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($parts['query'])."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
fwrite($fp, $out);
fclose($fp);
}
}
?>
NOTE: Make sure that in your MYCTRL/MYMETHOD function you have
ignore_user_abort(true);
that way when you fsocket connection is closed, your script will still run to the end.
We actually have a bunch of these fsockets for various reasons. If you need to make sure that the call to that controller/method came from the cron script, you need to pass some additional hash values so that only cron and the script know it. Once the script is called it has access to any codeigniter functions. Works like a charm.
I've set up 100s of CI cronjob on shared hosting like this: create a short php script which calls the CI controller as if it was a webbrowser.
So, script.php contains this:
script #! /usr/local/bin/php -f /home/example/public_html/script.php
<?php
get_get_contents('http:example.com/cronjob/');
?>
Then set your cronjob in cPanel to call script.php
When it runs Script.php will call the Codeigniter Cronjob controller. There you have the entire CI framework at your disposal.
If you are going to call it like a web browser, why not replace the cronjob
command with:
wget http://example.com/cronjob/
instead of creating something new or simply
curl --suppress http://example.com/cronjob/`

How to set date.timezone for CodeIgniter to work with php 5.3

When date.timezone in php.ini is commented out, it gives me:
A PHP Error was encountered
Severity: Warning
Message: main(): It is not safe to
rely on the system's timezone
settings. You are required to use
the date.timezone setting or the
date_default_timezone_set() function.
In case you used any of those methods
and you are still getting this
warning, you most likely misspelled
the timezone identifier. We selected
'America/Los_Angeles' for '-8.0/no
DST' instead
Filename: controllers/helloworld.php
Line Number: 2
When I have
date.timezone = "America/Los_Angeles"
It gives me this:
Server error The website encountered
an error while retrieving
http://localhost/ci/index.php/helloworld.
It may be down for maintenance or
configured incorrectly. Here are some
suggestions: Reload this web page
later. HTTP Error 500 (Internal Server
Error): An unexpected condition was
encountered while the server was
attempting to fulfill the request.
I am using php 5.3, CodeIgniter 2.0.0, and Apache 2.2.
Update 1:
I tried loading a test.php without CodeIgniter, where the first 3 lines of test.php is
date_default_timezone_set('America/Los_Angeles');
echo date("l j \of F Y h:i:s A");
And it works fine, different timezones also works fine too.
So I suspect the problem is from CodeIgniter.
If you Googled "CodeIgniter PHP 5.3" you would have found this article pretty quickly :)
http://philsturgeon.co.uk/blog/2009/12/CodeIgniter-on-PHP-5.3
To fix this, you only need to edit the main index.php for your CodeIgniter application:
if( ! ini_get('date.timezone') )
{
date_default_timezone_set('GMT');
}
This modification is something you will probably need to make for any CodeIgniter application running on PHP 5.3 and can easily be modified to your local timezone. There is a full list of supported timezones in the PHP manual here.
Yes, if you cannot directly edit the php.ini file, placing...
ini_set('date.timezone', 'America/New_York');
...as the first line in CI's index.php works fine.
Reference: PHP's Available Timezones
write in your index.php codeigniter...
/*
|---------------------------------------------------------------
| TimeZone
|---------------------------------------------------------------
|
| default Time Zone
|
*/
if ( function_exists( 'date_default_timezone_set' ) )
date_default_timezone_set('Asia/Jakarta');
Running well in my codeigniter
this is the simple way to do it
$timezone = "Asia/Calcutta";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
//echo date('d-m-Y H:i:s');
$localtime=date('H:i:s');
$sql="INSERT INTO hits (ip,edate,curtime,page_name) VALUES ('$ip', CURDATE(),'$localtime','$filename') ";
date.timezone is intended to go in your php.ini or .htaccess file.
you could do an ini_set('date.timezone', 'America/Los_Angeles'); in the first line of your script and get the desired results.
edit your config.php file
from
$config['time_reference'] = 'local';
to
$config['time_reference'] = 'UTC';

Resources