开发者

PHP script run via cron does not connect to database

开发者 https://www.devze.com 2023-04-06 12:40 出处:网络
I am trying 开发者_如何学Cto connect to mysql database in a PHP script run via cron job. It does not connect to the database somehow. I run the same script in my browser and everything works well. I u

I am trying 开发者_如何学Cto connect to mysql database in a PHP script run via cron job. It does not connect to the database somehow. I run the same script in my browser and everything works well. I use free BSD and following is the piece of code I try to run:

ini_set(max_execution_time,1200);
require_once("../settings.php");
$query = "insert into cron_log values(null, '". date("D d-m-Y") ."')";
mysql_query($query);
exec("convert /usr/local/www/demo/cron/test.pdf /usr/local/www/demo/cron/1.jpg");

If I run the above script via cron, it does nothing.

If I run above script in browser, it creates new row in table as well as creates 1.jpg.

If I remove the Database part and run it via cron, it creates the 1.jpg file.

What can be the possible cause and solution?


Note that CLI does not change the current working dir. Also cron does not set it. So doing your reqire_once call relative goes to a "random" location. Try a full path:

require_once(__DIR__."/../settings.php"); // PHP >=5.3
require_once(dirname(__FILE__)."/../settings.php"); // PHP <5.3


The most likely cause of this is that the script fails at the require_once("../settings.php"); line. This is because the working directory for the script when called through cron is not the same as the working directory when called through a browser.

Change ../settings.php to the full path, e.g. /path/to/settings.php to confirm that this is the problem.

It is also worth changing your cron line to php /path/to/script.php >> /path/to/logfile.txt 2>&1 so that logfile.txt will be filled with the output of your script. Make sure you turn display_errors on to catch any error messages!


My guess is that when you run it from cron you are not in the right directory and the settings.php file is not found; therefore the whole thing fails.

When you run it from cron, make sure the script cds to the appropriate directory so that settings.php is found using the relative path.


Any displayed error? Be sure you are referring to correct folder for file "settings.php" printing "getcwd()". When executing from cron script starts as located in "/"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号