Development

Creating PHP cron jobs on Ubuntu

Running cron jobs on your Ubuntu server to call PHP scripts in a timely manner.

The first step would be creating a PHP file that when called will leave proof that it was run. This could be creating a text file, doing a log entry or inserting something into a database.

Lets assume /var/html/some.php has

<?php
$myfile = fopen("CRONJOBMADETHIS.txt", "w") or die("Unable to open file!");
$txt = "IT WAS A SUCCESS\n";
fwrite($myfile, $txt);
fclose($myfile);

Which will make a text file when called on.

Next find out where your PHP binary is by using:

whereis php

Depending on how many versions of PHP you have installed the output will show the directories that contain “php” mine was:

It is very common for the directory to be just /usr/bin/php.

crontab

Now to set the cronjob by using crontab

sudo crontab -e

Opens the utility, make your way to the bottom and add the following:

* * * * * /usr/bin/php -f /var/html/some.php

In short this will call some.php every minute.

After a minute of waiting check if the proof was left that it was called. If you used the code above a text file should be made called CRONJOBMADETHIS.txt

If it worked then congratulations, check out crontab guru to learn the timming syntax.

If it did not work, check the cron status with

service cron status

Shows as inactive? start it with

service cron start

View the latest cron tasks by using:

grep CRON /var/log/syslog

If it still isnt working for you try using www-data as the cron user

sudo su -c "crontab -e" www-data

and reapeating the command. Even try just php instead of the full path.

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago