Cybrus
Cybrus

Reputation: 84

PHP Cron-Jobs timeout error

i am using a free domain to host my very humble website that has nothing besides 1 php/html page and 1 php script.
The imagechange.php script is as follows:

<?php
unlink("images/show.png");
$images = glob("images/*.png");
copy($images[rand(0,count($images))],"images/show.png");
?>

*each time it runs, it should switch show.png to a different image from the directory.

When i directly access the page (from URL bar) the script works perfectly. I mean, nothing shows up on the screen but the image does indeed change.

My hierarchy looks like so: ~/public_html/imagechange.php

When i used the built-in cronjob options in my free domain it said i set it to each 5 minutes, and it would execute the following command: php -f /home/a3638901/public_html/imagechange.php

FTP Folder hierarchy

I let it run for hours and it wouldn't change a thing. I thought to myself, well, maybe it's just the bad host. So i used an external service which allows me to do the same. This time i set it to each 10 minutes, and each time it would plot Timeout error.
Error log I really have no clue what could be possibly the problem with the script, or the cronjob.

Would appreciate guidance or troubleshooting, thanks in advance.

Upvotes: 0

Views: 1432

Answers (1)

Matijs
Matijs

Reputation: 2553

This is because your cron jobs runs from a different directory.

Depending on you PHP version you can either add a new line after <?php:

chdir(__DIR__);

or for older versions:

chdir(dirname(__FILE__));

This will change nothing when running from the webserver, but will make sure your cron job runs from the right directory.

However: some webservers have a security feature that does not allow you to freely change the directory when running on the server. In that case you will get an error that you can prevent by changing the directory only when running on the command-line:

   if (php_sapi_name() == "cli") {
     chdir(__DIR__);
   }

Upvotes: 1

Related Questions