If I type crontab -l in the command-line I can see the following line:
# * * * * * /usr/bin/php /home/user/every_minute_script.php
To start this cronjob, I need to edit the file using crontab -e command, remove the comment character at the beginning of the line, save the edited file, and exit the editor.
To stop this cronjob, the same steps, but adding the comment character at the beginning of the line.
I want to achieve exactly the same effect using a PHP script, instead of manually editing the file.
I did some research and found in a forum, the following message:
So, I have tried something, and it worked. I will paste the working code below:
As it is, we have a single script named
cron.phplocated at/home/userfolder, set to be executable (chmod a+x cron.php) and called from the command-line (PHP-CLI). Later I will tweak it to run from the web, which is my intent.Usage:
./cron.php activateto enable the cronjob and./cron.php deactivateto disable it.The script sets the EDITOR environment variable properly (to itself) and then calls
crontab -e, which on its turn calls the EDITOR (which is now the same cron.php script) passing the temporary crontab file location as an argument. Then, the proper crontab line is found and changed, and the modified version is saved, substituting the temporary file. When the script exits, crontab will update.This does exactly what I wanted, and fit my needs.
The other answers are nice and may fit different needs and scenarios, and I want to thank everybody who contributed.