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.";
}
?>
The following crontab entry:
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:So you should make sure that the script is executable for the user that runs the crontab, and the file contains shebang, e.g.:
Alternatively, run the script by explicitly invoking the
php
executable:If
php
is not available inPATH
, either specify the full path tophp
, or add the appropriate path to thePATH
environment variable. The most popular implementations allow to setPATH
via crontab, e.g.:(before the entries with the commands.)