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.
Related
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
I've burned more hours than I care to admit trying to figure this out :) A file is created successfully, however it is either 0 bytes or includes the mysql man page. I cant seem to get this to execute correctly or get an error message out.
The query executes correctly in MySQLAdmin. I can replace the mysql call with ls and it pipes a listing of the files into my output file. The host, user, and password strings are all correct and formatted well. Leads me to believe there is something wrong with my syntax?
$command = 'mysql --host=localhost --user='.DBASEUSER.' --password='.DBASEBPSWD.' --database='.DBASE.' -execute=SELECT Real_acct.Mail_Addr_1 from Real_acct > ../outputfiles/output.txt';
$returnVal = system($command, $returnVal);
You only have one dash (-) before your execute parameter. You would probably also need double quotes around your query statement:
$command = 'mysql --host=localhost --user='.DBASEUSER
.' --password='.DBASEBPSWD
.' --database='.DBASE
.' --execute="SELECT Real_acct.Mail_Addr_1 from Real_acct" > ../outputfiles/output.txt';
$returnVal = system($command, $returnVal);
Oh my good lord. I am trying to update some coding left behind by the previous programmer. The issue I'm running into is that when I try to write an SQL statement, the asterisk gets replaced by a file listing.
he previous guy liked to run PHP scripts like shell scripts. (If all you have is a hammer...) So, this is running from the command line.
// Here's Jason's additions. We add split comissions to the splits table and merge them with the records coming out of GP.
$jemsql = "select * from splits where salesPerson = '$salesCode'";
print "JemSQL: ".$jemsql."\n\n";
$sp_data = $mysql->query($jemsql);
$headData = array_merge($headData, $sp_data);
Basic PHP, right? Well, I keep getting an SQL error and the logging reveals...
select MJS_new.report.php OLE Spreadsheet Spreadsheet_Excel_Writer-0.9.2.tgz (long file listing...)
from exception where salesPerson = 'JD'
I went back and ran his original script, and the problem is OEM. He has the same problem in the same place.
Help me out here, why is the asterisk returning a file listing? How can the asterisk get overwritten? Is there something I can do to stop this behaviour? More code if needed, but I am stumped. How does this even happen?
EDIT:
I have minimized the file, keeping only what is absolutely needed:
#!/usr/local/bin/php
<?
date_default_timezone_set("America/New_York");
$db_host = 'datasrv';
$db_user = 'XXXX';
$db_pass = 'XXXX';
$db_name = 'financials';
mysql_connect($GLOBALS["db_host"], $GLOBALS["db_user"], $GLOBALS["db_pass"]) or die('Could not connect: ' . mysql_error());
mysql_select_db($GLOBALS["db_name"]) or die('Could not select database'.$db);
// Here's Jason's additions. We add split comissions to the splits table and merge them with teh records coming out of GP.
$jemsql = "select * from splits where salesPerson = '".$salesCode."'";
print "JemSQL: ".$jemsql."\n\n";
$sp_data = mysql_query($jemsql)
?>
When I run this with the shell script that is normally used to kick it off, here's the output:
JemSQL: select MJS_new.report.php OLE Spreadsheet Spreadsheet_Excel_Writer-0.9.2.tgz (long file listing) from splits where salesPerson = ''
If I just run it from the command line:
/usr/local/bin/php ./min_report.php JD test.pdf
JemSQL: select * from splits where salesPerson = ''
Here's the shell script that calls it:
for salesPerson in ${sales[*]}; do
fileTarget="$mountTarget$salesPerson/$fileName";
dirTarget="$mountTarget$salesPerson/";
out=`/usr/local/bin/php ./min_report.php $salesPerson $fileTarget`
echo $out;
out=`cp reports/$salesPerson.xls $dirTarget`;
echo $out;
echo $salesPerson;
cnt=`expr $cnt + 1`
done
So, at least I'm clued in to the problem... And I'm quite curious to know why he chose that "echo" method of running a command in the bash shell.
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';
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)