Run cron job in CodeIgniter and Hostgator

2019-04-13 00:26发布

问题:

I'm trying to run the follow cron job in codeigniter and hostgator

/usr/bin/php /home/username/public_html/index.php cronjob contact martin

But nothing happens, I receive the following email:

<h4>A PHP Error was encountered</h4>

<p>Severity: Notice</p>
<p>Message:  Undefined index:  REMOTE_ADDR</p>
<p>Filename: core/Input.php</p>
<p>Line Number: 351</p>

<p>Severity: Warning</p>
<p>Message:  Cannot modify header information - headers already sent by (output started at /home/iglesias/public_html/mysite.com/system/core/Exceptions.php:185)</p>
<p>Filename: libraries/Session.php</p>
<p>Line Number: 675</p>

My controller is as follows (simply sending an email to test).

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Cronjob extends CI_Controller {

function __construct()
{
    parent::__construct();
    $this->cron();
}

function cron()
{
    if(!$this->input->is_cli_request())
    {               
        die();
    }
}

function contact($name)
{
    $this->load->library('email');
    $config['mailtype'] = 'html';
    $this->email->initialize($config);

    $this->email->from('test@gmail.com', $name);
    $this->email->to('test2@gmail.com');
    $this->email->subject('test');
    $this->email->message('test sent');             
    $this->email->send();
}
}

Am I doing something wrong? I would really appreciate your help.

I changed the .htaccess to remove the index.php when called from URL, I don't know if this has something to do.

Thanks

回答1:

have you setup the correct route in config/routes.php? Try running the script from your browser (or commenting out the execution part) to make sure it's accessible with your current route/htaccess setup.



回答2:

my answer comes a long time after, but it could help other people. This error is apparently well known, but there is only a quick fix for it : http://ellislab.com/forums/viewthread/227672/ It says that it happens when you autoload session library, it calls CI_Input::ip_address() which is not initialized or something like that. The quick fix is in the input class (core/Input.php Line 351 (CI 2.1.2)) :

$this->ip_address = $_SERVER['REMOTE_ADDR'];

become :

if(isset($_SERVER['REMOTE_ADDR']))
   $this->ip_address = $_SERVER['REMOTE_ADDR'];
else
   $this->ip_address = '0.0.0.0';

Hope this helps.



回答3:

Check to see if Hostgator is running Apache as Fast-CGI instead of module. If that is the case, the run path to PHP may be different from what you are using.

You might see the relevant information if you check phpinfo.



回答4:

Great answer by @mariek

But we can also do this by just using @ sign before the syntax.

So Just made a little change in "core/Input.php" Line #352 (CI ver. 2.2.2)

$this->ip_address = $_SERVER['REMOTE_ADDR'];

to

$this->ip_address = @$_SERVER['REMOTE_ADDR'];

and its done.