Setting up Cron job using PHP script [duplicate] - php

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 7 years ago.
I am beginner in programming and I was trying to set up Cron Job using PHP script in couple ways, which I found on the internet, but I always run into some errors I can't fix by myself:
First method:
exec('echo -e "`crontab -l`* * {$_POST['birthDay']} {$_POST['birthMonth']} * /home/jharvard/vhosts/pset7/public/{$_POST['lastname']}{$_POST['firstname']}.php" | crontab -");
,but I think error appears because of ` symbol and I am sure a lot of ' symbols os not good either.
Second method:
echo "* * {$_POST['birthDay']} {$_POST['birthMonth']} * /home/jharvard/vhosts/pset7/public/{$_POST['lastname']}{$_POST['firstname']}.php" | tee -a /var/spool/cron/root
Error is: ( ! ) Parse error: syntax error, unexpected 'var' (T_VAR) in /home/jharvard/vhosts/pset7/public/calendar.php on line 24
Third try:
$cron_file = "{$_POST['lastname']}{$_POST['firstname']}";
// Create the file
touch($cron_file);
// Make it writable
chmod($cron_file, 0777);
// Save the cron
file_put_contents($cron_file, "* * {$_POST['birthDay']} {$_POST['birthMonth']} * /home/jharvard/vhosts/pset7/public/{$_POST['lastname']}{$_POST['firstname']}.php");
//Install the cron
exec('crontab cron_file');
I have no idea why this one doesn't work. I execute
crontab -l
, but it doesn't show any new jobs

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.

You can do it like this
$command = " * * * * * php PATH_TO_YOUR/some.php ";
exec('echo -e "`crontab -l`\n'.$command.'" | crontab -', $result);
var_dump($result);
by this you can add to www-data's user crontab new command, which will run some.php every minute
for more information here is reference about crontab - http://www.adminschoice.com/crontab-quick-reference , you need to read it to understand what to do with * * * * * (which are responsible for cronjob running time) and how to build correct $command with usage of php,sh and other scripts

Related

view details of atq from command line

I'm trying to generate a series of AT jobs from a script that logs into a database, gets some info and then loops over it and creates the needed jobs. I cannot seem to figure out the syntax for making it work. Here's what I have:
$tt_reminder below is the script i want to run with the arguments appended at the end of the string.
$tt_reminder = 'php /public_html/event-registration/scr/fireEventEmail.php' . ' ' . $event->Id . ' ' . 'TeleTraining-Reminder';
$tt2_at is the time that i want to schedule the at job for.
$tt2_at = '13:00 Feb 20, 2015';
This is the command i'm trying to execute the above with:
exec('echo -e `'.$tt_reminder.'` | at '.$tt2_at);
The problem is, it executes if immediately, rather than scheduling it.
Any ideas on what I'm doing wrong?
There are two possible problems with your at command.
Firstly, please try to set the date in this format:
$tt2_at = '2:30 PM 10/21/2014'
and secondly, it is highly recommended to provide the full path to at:
exec (echo ... | /usr/bin/at '.$tt2_at);
Like shown above, it should run. If you see a message like
Garbled time
your time string is wrong.

In php cron syntax url i have two parameters passed but it gets one parameter

this my url cron syntax
1.* 30 * * wget http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3&value=1.99
its gets only one argument that is first argument
the second argument its not displayed
iam using $_REQUEST['userId'];
and $_REQUEST['value'];
and another thing is iam changing the values first argument is value second argument is userId its displayes value but it not display userId
30 * * wget http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3&value=1.99
its get only first argument the second argument its not get
i want to get two arguments how can i get
please help me
thanks for advance
In bash & is special character and tells the shell to put the process in the background, so nothing after the & is read. you need to escape your string
30 * * * * wget http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3\&value=1.99
or
30 * * * * wget "http://myappone.com/universitysaver/scripts /signUpForm3.php?userId=49crbrGzdPk3&value=1.99"

GET php data to a commandline prompt

A PHP application on the server is saving a certain document with a sequential number into a MySQL database. How to obtaion that sequential number to a command line prompt that initiates the local doocument scanner?
ex:
c:\myscan ask_for_current_seq_nmbr.pdf
myscan is something written in c that takes care of the PC stuff. Only the name of file is unknown.
Some code (from the query PHP file)
$query = "SELECT last_seq FROM seq_table WHERE cat = 1";
$result = mysql_query($query, $link) or die('ERROR: '. mysql_error().'<br />ON LINE: '.__LINE__);
while($row = mysql_fetch_assoc($result)) {
echo $row['last_seq'];
}
!!! NOTE !!!
I am fetching a page from a remote server. ex. www.site.com/query.php?q=SELECT * FROM...
And that selection results in the last used sequential number which I would like to use in my command prompt.
!! UPDATE !!
We HAVE to go through a PHP file on the remote server to avoid having to use Remoote MySQL which has to be enabled on an IP basis.
You can call processes that run on the commandline with various function from PHP from the exec familyDocs.
If you're having problems building the actual command string, you can do with:
$cmd = sprintf('c:\myscan %d.pdf', $sequential_number);
As you write that the script is already writing it into the db with the $sequential_number I assume you have it already.
In case the database generates the number, then probably as the primary key. See mysql_insert_idDocs for obtaining the id.
Okay judging by the backslash and the C:\ I am guess you're using windows.
You are going to have to combine the following:
http://dev.mysql.com/doc/refman/5.5/en/mysql.html
How to store the result of a command expression in a variable using bat scripts?
and then to access the content of the variable you created use the %VARIABLE_NAME% syntax.
You should have flag in your mysql table like is_processed with value = 0 or 1.
When scan starts it runs query:
SELECT * FROM TABLE where is_processed = 0 order by sec_number
After processing you should run query:
UPDATE TABLE set is_processed = 1 where sec_number = 'sec_processed_number';

random cron job

I need a script1 that will execute script2 at random times a day.
I'm looking to execute the script2 around 30 times a day within random times.
script1 will be set in the cron job.
Could someone please help how to make it happen?
PS I am not a programmer, so would need something ready to go, please
Seth's solution certainly works, but the number of executions per day will differ. If you want definitely 30 executions, not more and not less, I propose using a cron entry like
0 0 * * * gen-executions.sh
and a script gen-executions.sh:
#!/bin/bash
for number in $(seq 30)
do
hour=$(( ${RANDOM}*24/32768 ))
minute=$(( ${RANDOM}*60/32768 ))
at -f /path/to/script.sh $(printf "%02d" ${hour}):$(printf "%02d" ${minute})
done
This generates exactly 30 executions of /path/to/script.sh at random times of the day using at.
* * * * * script1.sh
#!/bin/bash
if [ $(($RANDOM*100/32768)) -gt 2 ]; then exit; fi
exec php script2.php

Scripting a MySQL query in Unix using daemon in PHP

I'm trying to make an "at" job work at a given time, for testing purposes I'm using $time but this will be a datetime that I get from a separate MySQL query. In the command line I go like this:
echo "mysql -e 'UPDATE admin SET row1=row2 WHERE id=1;'" | at now
And I get a "job 36 at 2010-10-28 15:05". in PHP I tried going like this:
exec("\"mysql -e 'UPDATE admin SET row1=row2 WHERE id=1'\" | at $time");
But the query doesn't run. Worse, I have no idea what is happening.
echo exec('whoami');
returns "daemon" though. How can I echo whatever response I'm getting from the exec command? ideally I guess it would say "job 36 at 2010-10-28 15:05" or something similar.
Also, I have a .my.cnf file in my dir that specifies the db, login and password to use, does the daemon need to have one also for these to work?
[from the answers I can tell I wasn't clear about what I am trying to do. I need to
A. Run a mySQL query to get a date/time and an id
B. Schedule an update to take place to rows that match the id at the date/time
I'd already done "A" and was using "1" for the id and "now" for the time while testing. I'll look into PDO.
I'm not that familiar with the at command, but it seems to help run commands at a certain time.
If you're trying to write a scheduled script in PHP there are better ways to do it. Just write a CLI script and use the cron to schedule it. As Svisstack notes, if you're running MySQL queries use an in-built function such as PDO rather than system commands.
If you're just running systems commands, I'm not sure why you're using PHP ;)
Are you perhaps in safe_mode? If yes then your | is getting escaped automatically. Per the manual:
With safe mode enabled, the command
string is escaped with
escapeshellcmd(). Thus, echo y | echo
x becomes echo y \| echo x.
You can get more information by using the other parameters for the exec command. Try running this and see the output.
$output = array();
$return = false;
$last_line = exec("\"mysql -e 'UPDATE admin SET row1=row2 WHERE id=1'\" | at now", $output, $return);
var_dump($last_line);
var_dump($output);
var_dump($return);
Also, it looks like when you ran it at the command line, you echo'ed the MySQL command, but when you put it in the PHP code, it's not doing the echo anymore. I'm not sure if that makes a difference since I'm not to familiar with at, but I thought that I could offer some troubleshooting help.
$last_line = exec("echo \"mysql -e 'UPDATE admin SET row1=row2 WHERE id=1'\" | at now", $output, $return);
A missing echo in your second statement / exec? (and I'd rather use popen / proc_open the at $time, and fwrite the command for at to execute (after which you close the input stream, then the program. Use atq to verify wether it worked, and be aware the current use may be disallowed at jobs (normally found in files like /etc/at.allow or /etc/at.deny)

Categories