Reputation: 1813
I am trying to 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?
Upvotes: 1
Views: 4416
Reputation: 88667
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!
Upvotes: 2
Reputation: 11
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 "/"
Upvotes: 1
Reputation: 15969
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
Upvotes: 4
Reputation: 63966
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.
Upvotes: 1