Creating a crontab from within a PHP script
Moderator: General Moderators
Creating a crontab from within a PHP script
I need to setup a crontab from a PHP script. I'm thinking I should use the shell_exec() command, but the crontab needs to be setup for a specific user. Any suggestions?
Ok, I actually figured this out on my own, but I thought I'd post my solution in case anyone else needs to do it.
A few pre-requisites... server must have cPanel installed, PHP w/ cUrl extension (I'm using PHP5, but it'll probably work on PHP4), and you'll need to know the cPanel username/password for the domain you want to install the crontab for. Here's the code:
Hope this helps anyone. I needed it for an install script for a CMS I'm writing. This way, if it is installed on cPanel sites, the end-user doesn't need to know anything about cron for the crontabs to get setup correctly. 
A few pre-requisites... server must have cPanel installed, PHP w/ cUrl extension (I'm using PHP5, but it'll probably work on PHP4), and you'll need to know the cPanel username/password for the domain you want to install the crontab for. Here's the code:
Code: Select all
<?php
$cpUser = 'user'; # the cPanel username
$cpPass = 'password'; # the cPanel password
$cpTheme = 'x'; # the cPanel theme being used (my server uses the X theme)
$ip = $_SERVER['SERVER_ADDR']; # the IP address of the website to add the crontab to
# if you have an SSL cert on your site, you might want to use https:// instead
$location = "http://$cpUser:$cpPass@$ip:2082/frontend/$cpTheme/cron/editcron.html";
# for info on what to put here, you'll need to read up on crontab usage
$data = array
(
'0-minute' => 0,
'0-hour' => '*/2',
'0-day' => '*',
'0-month' => '*',
'0-weekday' => '*',
'0-command' => 'php test.php',
'mailto' => 'your@email_address.com'
);
# putting the fields together in preparation of an HTTP POST
$fields = '';
foreach ($data as $k => $v)
$fields .= $k . "=" . $v . "&";
$fields = substr($fields, 0, strlen($fields) - 1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $location);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
if (empty($result))
trigger_error('Unable to submit: ' . @curl_error($ch), E_USER_ERROR);
echo $result;
exit;
?>