I need to automate a couple things for my website, one of them being having the database cleared at midnight every night. I looked at cron job tutorials and came up with a script
<?php
$con = mysqli_connect("localhost", "root", "password", "test");
$sql = "DELETE FROM markers";
$con->exec($sql);
echo "Record deleted successfully";
$con = null;
INSERT INTO `markers` (`name`, `lat`, `lng`, `id`, `questTitle`, `questReward`, `category`, `date_submitted`) VALUES ('Marker1', 41.2952, -92.644, 1, NULL, NULL, NULL, NULL);
this just wipes the database and re-inserts records with empty values to be modified throughout the day.
I tried setting up a cron job to run this at midnight using cpanel, my path is
/usr/bin/php /home/user/public_html/command.php
I have the command.php in my uploaded web files and set the job to run every 30 mins to test it, but no matter what I do I cannot seem to get it to work.
7
Answers
What i noticed is that you are using
/usr/bin/php /home/user/public_html/command.php
Have you tried just using the plain php command only?
30 * * * * php /path/to/php/file >> /path/to/desired/log/file/location
My assumption is that the php is not installed on
usr/bin
directory.If you want to run a PHP script located in the public_html directory, the correct cron command will be:
Or you can just use
curl request
as the cron job command.You can set cron in linux based server like that
0 0 * * * wget -O /dev/null your_url (http://localhost/test.php)
it will run at every mid night.
for set cron time please visit Crontab
Try any of these:
wget -O -q http://example.com/command.php
php /home/user/public_html/command.php
/usr/bin/curl http://www.example.com/command.php
Also, make sure you enter your email address in the Cpanel cron job so you can at least know that the script is being ran on schedule, if it is then the problem is probably somewhere else.
Also, in your code, there’s this line:
Putting this line literally in your script does nothing and should cause an error. You should execute this properly. E.g., Your script should look something like this instead:
You can simply use Your Hostinger Panel for doing the job.
https://www.hostinger.com/tutorials/cpanel/#How-to-Create-a-Cron-Job
Please check it out and you can help yourself from There.
Question of bounty poster:
My take on it probably you are getting permission issue on cron it is working for server user but not for cron try with below command to work with your apache-user I am assuming apache server is what you are using.
Or you can give the permission to required user or group to let them maniuplate directories and files something like below.
To run your script using a cron job the same way you do in the browser:
the -o redirects stdout, and “>/dev/null 2>&1” redirects stderr to stdout, which will let you see both the results and any errors in the command.log file.