Why isn't my cron job Not running my PHP script?

524 views Asked by At

I am running Ubuntu 16.04 OS and LAMPP inside it. I want to schedule a cron job to run every minute, and execute a PHP script. So this is what I did:

Opened terminal and entered crontab -e

It opened the CronTab file in VIM and I pressed ESC to enter the INSERT mode and then wrote the following command:

* * * * * /opt/lampp/htdocs/Tests/16RunAPHPScriptInCronTab/index.php

Then I pressed :wq to Save and Exit. Got installing new crontab notification in terminal.

Now my actual script should check a directory in LAMPP local server for the presence of a .pdf or .docx file and if it does, then it should do some further work, but since to start with that, I needed to check if the cron job is actually running every minute. So what I did is that made my script do this:

If a file with the extension .pdf pr docx exists in the directory, it deletes them. That way I will know if the cron job has run.

But this does not seem to work. A .pdf file is very much there and it is not getting deleted. So how would I know if my cron job is running correctly?

The sources of my learning to do this are this, this, this and this.

<?php

$pdfFileName = 'dumps/*.pdf';

$docxFileName = 'dumps/*.docx';

if ( (count(glob($pdfFileName)) > 0)   ||   (count(glob($docxFileName)) > 0) ) {

    /***********************************************/
    /*************** if the file exists ************/
    /***********************************************/

    if (file_exists($pdfFileName)) {
        unlink($pdfFileName);
    }

    if (file_exists($docxFileName)) {
        unlink($docxFileName);
    }

} else {
    echo "File does not exist.";
}

?>
2

There are 2 answers

13
Ruslan Osmanov On BEST ANSWER

The following crontab entry:

* * * * * /opt/lampp/htdocs/Tests/16RunAPHPScriptInCronTab/index.php

means that /opt/lampp/htdocs/Tests/16RunAPHPScriptInCronTab/index.php command is run every minute just as if you typed this string in terminal and pressed Enter. The command will fail, if at least one of the following is true:

  • the current user has no execution permissions for the file/directory;
  • the file is not a shell script, and the shebang is not specified

So you should make sure that the script is executable for the user that runs the crontab, and the file contains shebang, e.g.:

#!/usr/bin/php

Alternatively, run the script by explicitly invoking the php executable:

* * * * * php /opt/lampp/htdocs/Tests/16RunAPHPScriptInCronTab/index.php

If php is not available in PATH, either specify the full path to php, or add the appropriate path to the PATH environment variable. The most popular implementations allow to set PATH via crontab, e.g.:

PATH=/bin:/sbin:/usr/sbin:/usr/bin:/opt/bin:/usr/local/bin

(before the entries with the commands.)

7
LF-DevJourney On
* * * * * php /opt/lampp/htdocs/Tests/16RunAPHPScriptInCronTab/index.php