Reputation: 1593
I want to run a cron job. My application is developed in PHP and Mysql.
In browser if i use $_SERVER[HTTP_HOST]
in coding, it works fine. But if I use the same thing in cron job it is giving errors.
Can any body give suggestion to fix this?
Upvotes: 21
Views: 16327
Reputation: 2255
If wget is supported on your server, you can change your cronjob from
15 * * * * php -q /path/to/your/cron/script.php > /dev/null 2>&1
to
15 * * * * wget -qO- --no-check-certificate "https://example.com/cron/script.php"
Be sure to limit the number of tries, and the time limit.
Consult the manual for the available options.
Upvotes: 0
Reputation: 359
I'm surprised no one has mentioned the option of just defining any required values for the _SERVER array in another file and then just including that. This is the quickest way I've found to run a normally cgi-based php script from the cli for quick test/debugging purposes.
Eg, file cron_server_wrapper.php
:
<?php
$_SERVER['SERVER_NAME'] = "localhost";
$_SERVER['HTTP_HOST'] = "localhost";
$_SERVER['REMOVE_ADDR'] = "10.20.30.40";
$_SERVER['DOCUMENT_ROOT'] = "/";
$_SERVER['HTTP_REFERER'] = "/crontab-foo";
Then run:
/usr/bin/php -B "require 'path/to/cron_server_wrapper.php'" -E "require 'my_php_cron_script.php';" < /dev/null
Upvotes: 4
Reputation: 3063
Adding hard coded args into the crontab didn't help as I need it to be sensitive to different environments
So >= PHP 5.3.0 you can use gethostname()
http://php.net/manual/en/function.gethostname.php
Upvotes: 4
Reputation: 32731
$_SERVER['HTTP_HOST']
is not populated when running it from a cronjob, the file is not accessed via HTTP.
You will either have to hardcode the Host or pass it via a command line argument and access it via the $_SERVER['argv']
array.
Upvotes: 20
Reputation: 6950
Try running cron job with curl .. It will populate your $_SERVER['HTTP_HOST'].
syntax on linux is like
curl http://yourdomain/yourfile.php
Upvotes: 7
Reputation: 6013
As previously stated, $_SERVER is not present when you run php via php-cli.
Though, there is an option to run your cron'd scripts in php-cgi, where you will have $_SERVER. If you curl to a local web server, then $_SERVER will be populated.
$ cat /etc/cron.daily/mydailyphpwork
/usr/bin/curl http://domain.tld/path/to/cron-script.php &> /dev/null
However, I think you should indeed stick with the solutions proposed by TimWolla or DerVO, unless you really need this behaviour.
Pros:
Cons:
Upvotes: 6
Reputation: 3679
When php is executed on the command line, $_SERVER['HTTP_HOST']
is (of course) not available.
You can just suppress the error using the @
sign or be a bit more cautious using a construct line:
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'CLI';
Upvotes: 7
Reputation: 309
You can hard code the value of $_SERVER[HTTP_HOST]
if it is empty, or you can perform some other check.
Upvotes: 2