Cron Job $_SERVER issue

生来就可爱ヽ(ⅴ<●) 提交于 2020-01-12 03:05:33

问题


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?


回答1:


$_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.




回答2:


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';



回答3:


Try running cron job with curl .. It will populate your $_SERVER['HTTP_HOST'].

syntax on linux is like

curl http://yourdomain/yourfile.php



回答4:


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:

  • You will get all $_SERVER variables set as expected.
  • If you need to rewrite a lot of code with if-else's this might be preferred as you don't need to change any code.

Cons:

  • It is kind of a workaround and probably means a slight increase in cpu load.



回答5:


You can hard code the value of $_SERVER[HTTP_HOST] if it is empty, or you can perform some other check.




回答6:


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




回答7:


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


来源:https://stackoverflow.com/questions/9128488/cron-job-server-issue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!