Use PHP to create, edit and delete crontab jobs?
crontab command usage
usage: crontab [-u user] file
crontab [-u user] [ -e | -l | -r ]
(default operation is replace, per 1003.2)
-e (edit user's crontab)
-l (list user's crontab)
-r (delete user's crontab)
-i (prompt before deleting user's crontab)
So,
$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.'* * * * * NEW_CRON'.PHP_EOL);
echo exec('crontab /tmp/crontab.txt');
The above can be used for both create and edit/append provided the user has the adequate file write permission.
To delete jobs:
echo exec('crontab -r');
Also, take note that apache is running as a particular user and that's usually not root, which means the cron jobs can only be changed for the apache user unless given crontab -u
privilege to the apache user.
Setting up Cron job using PHP script
Your first try got lots of problem:
- The string has started with single quotation, ended with double.
- variables inside strings that started with double quote will be parsed. so if you start your string with single quote, variable won't replace with their values.
- you can not use single quote character within a string started with single quote, unless you escape with backslash. (same apply to double quote as well) example:
$var = '\'test\''
So grammatically, your first try should be like this:
exec("echo -e \"`crontab -l`* * {$post['birthDay']} {$post['birthMonth']} * /home/jharvard/vhosts/pset7/public/{$post['lastname']}{$post['firstname']}.php\" | crontab -");
Better Solution
As I understand from your code, you want to do something on user's birthday.
A better solution is create one single cronjob manually, that will run one file every night, and that file will manage what to do (including who's birthday is that, sending them email, etc) instead of having a cronjob for every user.
Related Topics
Warning: Mysqli_Connect(): (Hy000/1049): Unknown Database in MAC Terminal Only
[Php][Mysql] How to Insert Data in 2 Tables At Same Time
How to Create Multi Level Category Hierarchy ( Category Tree ) - Codeigniter
How to Center the Text in Phpexcel Merged Cell
How to Prevent a User from Directly Accessing My HTML Page by Writing Url
Sending Post Requests Without Waiting for Response
Validating Base64 Encoded Images
How to Get Only Date from Datetime in Codeigniter
How to Check, If a PHP String Contains Only English Letters and Digits
Add Images to a Excel File Using PHP
Check If a Specific Value Exists At a Specific Key in Any Subarray of a Multidimensional Array
Preventing Direct Access to a PHP Page, Only Access If Redirected