Adding file to crontab via php script - php

I've found at this forum that it is possible to edit crontab like this:
a. crontab -l > $tmpfile
b. edit $tmpfile
c. crontab $tmpfile
d. rm $tmpfile
So, I'm trying to implement this solution on php:
include('Net/SSH2.php');
$ssh = new Net_SSH2('myhost');
if (!$ssh->login('user', 'password'))
{
echo'Login Failed';
}
$ssh->exec('crontab -l > /var/www/tmp.txt');
$content=file_get_contents("/var/www/tmp.txt");
$content.='0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php';
$file=fopen("/var/www/tmp.txt", "w");
fputs($file,$content);
fclose($file);
$ssh->exec('crontab /var/www/tmp.txt');
echo $content;
I can see edited content of crontab in my browser and tmp file, but when I use crontab -e it's not changed. What's my mistake?

I had to add new string before the end of file. In other case it's not added to crontab.
changed $content.='0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php';
to $content.="0 0 1 * * /usr/bin/php /var/www/clearPreviousMonth1.php\n";
note that it's neccessary to use " instead of ', because it just will append \n symbols to last string

Related

Create Scheduled Tasks under Plesk with php

I'm moving from a webserver with CPanel to one with Plesk. Under Cpanel, it's fairly simple to create and remove cronjobs with php:
<?php
// Create cron
$new_cron = "30 * * * * cd /home/account/public_html/; /usr/local/bin/php -f controller.php ".$argument1.PHP_EOL;
$output = shell_exec('crontab -l');
file_put_contents('/tmp/crontab.txt', $output.$new_cron);
exec('crontab /tmp/crontab.txt');
// Remove cron
$cronjob = "30 * * * * cd /home/account/public_html/; /usr/local/bin/php -f controller.php ".$argument1.PHP_EOL;
$output = shell_exec('crontab -l'); // pull current cron jobs
if (strstr($output, $cronjob)) // found
{
$newcron = str_replace($cronjob,"",$output); // delete it
file_put_contents('../tmp/crontab.txt', $newcron.PHP_EOL); // Save
exec('crontab ../tmp/crontab.txt'); // Send back
}
?>
Under Plesk I have scheduled tasks. How do I use PHP to create and remove those? Or is there another method?
You can schedule task at Home > Subscriptions > example.tld > Scheduled Tasks:
Since Plesk 12.5 there are options of task type:

How to find out the process or script which call php bash script

I have php bash script that do some database processing. All I need to know is the caller of this script. I don't know if it's process or other script. So is there some way to know process id or script name of caller?
Script is running by some process and its code starts with interpreter path "#!/usr/bin/php". This file called as bash script only.
OS: Centos 6.5
You can try something like this
<?php
Check for a current process by filename
function processExists($file = false) {
$exists = false;
$file = $file ? $file : __FILE__;
// Check if file is in process list
exec("ps -C $file -o pid=", $pids);
if (count($pids) > 1) {
$exists = true;
}
return $exists;
}
?>
This will check against the filename that you're trying to track. If you need the process id, just adjust what's in in the exec or return the $pids.
try this ---
$mystring = "script_running";
exec("ps aux | grep \"${mystring}\" | grep -v grep | awk '{ print $2 }' | head -1", $out);
print "The PID is: " . $out[0];
ps aux is more descriptive of what's running.

Bash how to get full script name from PID

I have this php function that checks the script's name from the given PID, and compares it to itself.
function isRunning($pid) {
$filename = exec('ps -p '.$pid.' -o "%c"');
$self = basename($_SERVER['SCRIPT_NAME']);
return ($filename == $self) ? TRUE : FALSE;
}
From what I know, I usually use this command to get the script name from the PID:
ps -o PID -o "%c"
It returns me the filename, but only the first 15 characters.
Since my script's name is
daily_system_check.php
the function always returns FALSE, because it's comparing itself with
daily_system_ch
Is there another bash command for Centos 6 that will return me script's full name?
You didn't specify what is your OS, but in Ubuntu Linux I can see full name of the script with adding --context to the ps call:
# ps -p 17165 --context
PID CONTEXT COMMAND
17165 unconfined /bin/bash ./testing_long_script_name.sh
#
read the the proc cmdline file:
cat /proc/$pid/cmdline | awk 'BEGIN {FS="\0"} {print $2}'
There seems to be no flag or collumn in "ps" command to show the whole filename without the filepath or it being cutoff. PHP's basename() gets the job done.
function isRunning($pid) {
$filename = basename(exec('ps -o cmd= '.$pid));
$self = basename($_SERVER['SCRIPT_NAME']);
return ($filename == $self) ? TRUE : FALSE;
}

exec not working or executing crontab script

Basically I have developed a small script that adds a cron job into a file called "crontask" and then I want to execute it so then it becomes a cron job. Here is the script:
<?php
$filename = "../../tmp/crontask.txt";
$output = shell_exec('crontab -l');
$something = file_put_contents($filename, $output.'* * * * * NEW_CRON'.PHP_EOL);
$cngDir = chdir('../../tmp/');
echo exec('crontab ' . getcwd() . '/crontask.txt');
//var_dump($exe);
?>
Everything is ok, the path is the same and if I copy and paste the path that prints out IT will carry out the cronjob but in PHP it won't???
Everything works, apart from the exec function, it doesn't execute it. Any ideas?
In terminal, if I do:
string(25) "crontab /tmp/crontask.txt"
it will execute it.
Try the following things:
Call to the command using the full command path. Sometimes $PATH is not set in the script environment and can't find the command if not.
Setup the working dir of the script using http://php.net/manual/en/function.chdir.php
Use the absolute path to access to the file
I've had a similar issue with cron jobs
I looked at your code and got a couple of ideas.
I used absolute paths
Here is my code:
$myFile = "/home/user/tmp/crontab.txt";
$addcron = "
0 0 * * * cronjob1 " . PHP_EOL .
"0 18 * * 1-5 conjob2 " . PHP_EOL .
"0 9 * * * cronjob3 " . PHP_EOL ;
$output = exec('crontab -l > ' . $myFile );
file_put_contents($myFile,$addcron ,FILE_APPEND);
echo exec('crontab ' . $myFile );
echo "<h3>Cron job successfully added!</h3>";enter code here
basically i wrote the list of previous cronjobs to a file and then appended the file with new cronjobs. Then added the new list of cronjobs with the crontab command.
the linux write to file command ' > ' was what did the trick ;)

crontab php file and output to log file result

cron line look's like:
*/1 * * * * /usr/bin/php /path/to/CRON.php > /path/to/log/CRON_LOG.txt 2> /dev/null
CRON.php
<?php
require_once 'config.php';
define('CRON', dirname(dirname(__FILE__)));
$parts = explode("/",__FILE__);
$ThisFile = $parts[count($parts) - 1];
chdir(substr(__FILE__,0,(strlen(__FILE__) - strlen($ThisFile))));
unset($parts);
unset($ThisFile);
$CRON_OUTPUT = "STARTING CRON # ".date("m-d-Y H:i:s")."\r\n";
$CRON_OUTPUT .= CleanLog() . "\r\n";
$CRON_OUTPUT .= "\r\n";
echo $CRON_OUTPUT;
$fh = fopen(''.CRON.'/log/CRON_LOG.txt', 'a');
fwrite($fh, $CRON_OUTPUT);
fclose($fh);
die();
?>
CleanLog function:
global $db;
$resp = '';
$db->query('SQL');
$resp = 'Deleted '.$db->rows_affected.' entries from table';
return $resp;
In file only these two lines showing and function by the time as i can see executed two times:
CRON_LOG.txt
STARTING CRON # 02-26-2012 21:26:01
Deleted 0 entries from table
STARTING CRON # 02-26-2012 21:26:01
Deleted 0 entries from table
What's wrong with it, why it only produce those lines and file doesn't updated (in file only date/time changing, nothing more, it should add more lines and even file size should grow up) ?
You should be using >> for redirection to append to the file, rather than > which overwrites the log each time the script runs.
*/1 * * * * /usr/bin/php /path/to/CRON.php >> /path/to/log/CRON_LOG.txt 2> /dev/null
##---------------------------------------^^^^^^
There really isn't any need to do fopen()/fwrite() inside the script itself, since the cron job is already handling the output redirection.

Categories