I am new with cron job in php,basically i want to send email to user on certain time of period.i want to send email daily,weekly,monthly,quarterly,yearly,or specific amount of days.
In smarty template i want to use this type of function
Can any body know how to do tihs?
CRON is based on the server. You can't run CRON jobs from within PHP. You have actually run it on the server. If you have shared hosting or something, you can usually set up CRON jobs via the administrative control panel or something similar.
It's possible to write to the webserver user's crontab from PHP, depending on security configuration.
$job = "* * * * * /bin/ls";
$p = popen("crontab -", "w");
$return = fwrite($p, $job, strlen($job));
pclose($p);
This will erase the contents of your existing crontab. You could read the existing job in first:
$p = popen("crontab -l", "r");
while ($crontab[] = fgets($p)) { /* ... */ }
pclose($p);
Then modify that as appropriate. You'll want your code to be idempotent so you can run it many times without worrying about what will happen.
Note that your host may not allow your PHP to do this, and even if it does, it may not be a good idea. As #Foo says, the best way is to just talk to cron directly. Get a shell session and run crontab -e, or see what you can do with whatever web interface you can get.
Related
I have a script that I run for multiple clients.
Same script, I'm just using a different GET variable to load the client credentials.
eg.
example.com/script.php?client=lego
example.com/script.php?client=nike
example.com/script.php?client=stackoverflow
I've setup multiple crons to hit the script at midnight, with each cron having a different client GET variable.
What would be the best way to run a single CRON but process all clients? So I don't need to setup a CRON each time for each client.
There can be various solutions but without knowing the code what comes to my mind is.
Delete all crons and setup just one.
example.com/script.php
Inside script.php wrap whatever you earlier had in a function, create an array of clients and call that function for every client by passing username. For example
<?php
// if you have lots of clients and script can exhaust time limit
ini_set('max_execution_time', 0);
$clients = ['lego', 'nike', 'stackoverflow'];
foreach ($clients as $client) {
myScript($client);
}
function myScript($client)
{
// Whatever you had in script.php earlier replacing $_GET['client'] with $client.
}
Hope it answers your question.
I am new to php, I am making a schedule page which is getting data form database. From database I am picking the send time and dates of the emails which have come. What am trying to do is that, if the send date and time has come the system should send email to that address.
For email sending i am using this API.
This is my Code what I should add in this to perform such functionality.
Am trying to get 3 things.
1. to fetch array from database whose time has been reached.
2. storing them in array using loop.
3. sending them email through a loop.
This is my code.
<?php
include('iSDK/src/isdk.php');
$myApp = new iSDK();
Test Connnection
if ($myApp->cfgCon("connectionName"))
{
echo "Connected...";
}
else
{
echo "Not Connected...";
}
$query = mysql_query('SELECT communication.senddatetime,emails.email
FROM communication
INNER JOIN emails
ON communication.communication_id=emails.communication_id
WHERE senddatetime <= NOW()'); //or die(mysql_error())
while($row = mysql_fetch_assoc($query)){
$email=array($fetch);
$result=mysql_num_rows($query);
for($i=0; $i<$result; $i++){
$obj=mysql_fetch_object($query);
$emailaddress=$obj->email;
}
for($i=0; $i<$result; $i++){
$conDat = array('FirstName' => 'Hassan',
'Email' => $email);
$conID = $myApp->addCon($conDat);
$clist = array($conID);
$email = $myApp->sendEmail($clist,'kamranasadi431#gmail.com','~Contact.Email~','ccAddresses', 'bccAddresses', 'contentType', 'JK', 'htmlBody', 'txtBody');}
}
?>
You should use cron jobs.
First, you must create a php script whose look if there is any email to be sent (it can be a simple php file that get the time and that compare it with a timestamp in your database, then get info about the email you want to send, compose the email with your headers, subject and body and finish it by sending it.)
Second you must execute it in shell (I assume you're working with a Linux system) to test if it is working ok. To execute a php in shell you can use the next command
php /route/to/your/php/script.php var1 var2 .... varN
Maybe the command php could not work so you must to know which php client you have installed (very important, you must first have installed a php client in your system -- apt-get install php5-cli). You can know which php have you installed in your system typing the next in a shell
which php
You will find more information about how to exec php in shell in the url Shell run/execute php script with parameters
And the third thing you must to do is to program the script in cronjob. For example, if you want to execute it in 5 minutes intervals you could write the next in your cron (crontab -e)
*/5 * * * * php /route/to/your/php/script.php var1 var2 > /dev/null
Or
*/5 * * * * /usr/bin/php /route/to/your/php/script.php var1 var2 > /dev/null
You have other option to make a php an exec file and so you mustn't use php before your script and it's to add the next line before you open your php
#!/usr/bin/php
<?php
Another way to schedule an email to be sent at a later time is by way of a system command combining sendmail with at, like so:
/usr/sbin/sendmail -f from#from.com to#to.com < message.txt | at 16:00 today
This may be a little cleaner than running a cron job every few minutes that queries a database for emails that need to be sent. You can run the above system command from your PHP script using php's shell_exec function.
If you don't have a server available on your end 24/7, you can also take the advantage of the cloud for your purpose.
An easy way to set-up this, is using Jenkins on a IaaS, or on PaaS, where you just need to create your job and specify when you would like to launch it, without installing or configuring anything.
A cron job configuration could be done in the way it is specified here. Complete step by step guide could be also find here.
I have a script to process sending emails. There could be thousands of emails to send. I want to show the user a page that says something along the lines of "Your messages are being sent.", but I don't want that page to do the actual sending of the messages, because I don't want the user to see a blank page until the script finishes and I also don't want the user to have to wait for the script to finish.
I would like to pass a list of IDs to another PHP page (lets call it run.php) and have it execute without having the user actually visit it. So I would pass the IDs to the page, which starts the execution, but then finishes loading the current page which shows the message "Your messages are being sent.".
<?php
/* SESSION DATA HERE */
executeMailSend($ids);
?>
<html>
<head>
....
</head>
<body>
Your messages are being sent.
</body>
</html>
I think I could something like this using ajax, but I would prefer to not make this rely on client side coding.
Also, if at all possible, I need to have the script running in the background keep session data from the session that starts it, and I would prefer that I don't have to pass this data along as separate variables.
Also, I don't want to use anything like exec() or system().
Any ideas?
Utilize the power of AJAX for more information checkout this tutorial by w3schools.com
http://www.w3schools.com/ajax/default.asp
A cron job is one option. You could do it by implementing a queue in the database, you'd just add entries for the mail to be sent and the cron job processes those entries. But maybe read this before going down that road: http://www.engineyard.com/blog/2011/5-subtle-ways-youre-using-mysql-as-a-queue-and-why-itll-bite-you/
If you use a cron job, you're going to be implementing a queue somewhere (flat file...blech, MySQL, other DB, etc.)
Why not use something that is actually made for queuing? For example you could use Amazon (http://aws.amazon.com/sqs/). But whatever software/provider you use, this sounds like it would be best with proper job queuing. You want the user to go to a page which will add some work items to your queue (which in this case are email addresses and maybe messages depending on exactly what you are doing). Then the queue software should have some means of processing these jobs (i.e. actually sending the emails).
You say you don't want to pass variables, but you'd likely have to send whatever data you need for each job to your queue. You could potentially store extra data to your database, just think about locking and performance.
You could make your script add that email to 'email query' and schedule a cron job to send emails. I don't think there is other way to call php script asynchronously.
Maybe this could point you in right direction: http://blog.markturansky.com/archives/205
if you have access to a linux box; you can use something called Cronjobs.
You can create a separate script with it's own database table, which it uses for reference.
on a set interval it runs PHP through the linux CLI for PHP and executes the script, no user needs to be on the page. the database needs to be configured properly though.
Only problem is with cronjobs, all output is emailed to the administration E-mail (/etc/aliases
Example on Cronjob input:
nano /etc/crontab
* * * * * root /usr/bin/php /var/www/cron.php
and on your cron.php you will have a script setup for a specific function, in this case. E-mail users.
http://www.thegeekstuff.com/2011/07/php-cron-job/
I guess I will have to stick with my current option which is script I've used before. I was hoping to find a better option, but here is the code I am going to use:
function backgroundPost($url){
$parts=parse_url($url);
$fp = fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80, $errno, $errstr, 30);
if (!$fp) {
return false;
} else {
$out = "POST ".$parts['path']." HTTP/1.1\r\n";
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($parts['query'])."\r\n";
$out.= "Connection: Close\r\n\r\n";
if (isset($parts['query'])) $out.= $parts['query'];
fwrite($fp, $out);
fclose($fp);
return true;
}
}
backgroundPost($siteURL.'/run.php?ids='.urlencode($ids).'&sessiondata='.urlencode($sessiondata));
Does anyone see a problem with using this? Security, bad code, etc?
Are you on Linux server? You can fork() the script (within PHP) then daemonize the child process, detaching it so that it continues to run after the initializing HTTP request is finalized. Just make sure to kill the child processes correctly.
http://www.re-cycledair.com/php-dark-arts-daemonizing-a-process
I need to build a system that a user will send file to the server
then php will run a command-line tool using system() ( example tool.exe userfile )
i need a way to see the pid of the process to know the user that have start the tool
and a way to know when the tool have stop .
Is this possible on a Windows vista Machine , I can't move to a Linux Server .
besides that the code must continue run when the user close the browser windows
Rather than trying to obtain the ID of a process and monitor how long it runs, I think that what you want to do is have a "wrapper" process that handles pre/post-processing, such as logging or database manipulation.
The first step to the is to create an asynchronous process, that will run independently of the parent and allow it to be started by a call to a web page.
To do this on Windows, we use WshShell:
$cmdToExecute = "tool.exe \"$userfile\"";
$WshShell = new COM("WScript.Shell");
$result = $WshShell->Run($cmdToExecute, 0, FALSE);
...and (for completeness) if we want to do it on *nix, we append > /dev/null 2>&1 & to the command:
$cmdToExecute = "/usr/bin/tool \"$userfile\"";
exec("$cmdToExecute > /dev/null 2>&1 &");
So, now you know how to start an external process that will not block your script, and will continue execution after your script has finished. But this doesn't complete the picture - because you want to track the start and end times of the external process. This is quite simple - we just wrap it in a little PHP script, which we shall call...
wrapper.php
<?php
// Fetch the arguments we need to pass on to the external tool
$userfile = $argv[1];
// Do any necessary pre-processing of the file here
$startTime = microtime(TRUE);
// Execute the external program
exec("C:/path/to/tool.exe \"$userfile\"");
// By the time we get here, the external tool has finished - because
// we know that a standard call to exec() will block until the called
// process finishes
$endTime = microtime(TRUE);
// Log the times etc and do any post processing here
So instead of executing the tool directly, we make our command in the main script:
$cmdToExecute = "php wrapper.php \"$userfile\"";
...and we should have a finely controllable solution for what you want to do.
N.B. Don't forget to escapeshellarg() where necessary!
I am writing a social cloud game for Android and using PHP on the server. Almost all aspects of the game will be user or user-device driven, so most of the time the device will send a request to the server and the server will, in turn, send a response to the device. Sometimes the server will also send out push messages to the devices, but generally in response to one user's device contacting the server.
There is one special case, however, where a user can set a "timer" and, after the given time has elapsed, the server needs to send the push messages to all of the devices. One way to do this would be to keep the timer local to the user's device and, once it goes off, send the signal to the server to send the push messages. However, there were several reasons why I did not want to do it this way. For instance, if the user decides not to play anymore or loses the game, the timer should technically remain in play.
I looked around for a method in PHP that would allow me to do something like this, but all I came up with were alarms, which are not what I need. I also thought of cron jobs and, indeed, they have been recommended for similar situations on this and other forums, but since this is not a recurring event but, rather, a one time event to take place at an arbitrary point in time, I did not know that a cron job is what I want either.
My current best solution involves a cron job that runs once a second and checks to see if one of these events is to occur in the next second and, if so, sends out the push messages. Is this the proper way to handle this situation, or is there a better tool out there that I just haven't found yet?
cron is great for scripts run on a regular basis, but if you want a one-off (or two-off) script to run at a particular time you would use the unix 'at' command, and you can do it directly from php using code like this:
/****
* Schedule a command using the AT command
*
* To do this you need to ensure that the www-data user is allowed to
* use the 'at' command - check this in /etc/at.deny
*
*
* EXAMPLE USAGE ::
*
* scriptat( '/usr/bin/command-to-execute', 'time-to-run');
* The time-to-run shoud be in this format: strftime("%Y%m%d%H%M", $unixtime)
*
**/
function scriptat( $cmd = null, $time = null ) {
// Both parameters are required
if (!$cmd) {
error_log("******* ScriptAt: cmd not specified");
return false;
}
if (!$time) {
error_log("******* ScriptAt: time not specified");
return false;
}
// We need to locate php (executable)
if (!file_exists("/usr/bin/php")) {
error_log("~ ScriptAt: Could not locate /usr/bin/php");
return false;
}
$fullcmd = "/usr/bin/php -f $cmd";
$r = popen("/usr/bin/at $time", "w");
if (!$r) {
error_log("~ ScriptAt: unable to open pipe for AT command");
return false;
}
fwrite($r, $fullcmd);
pclose($r);
error_log("~ ScriptAt: cmd=${cmd} time=${time}");
return true;
}
soloution 1 :
your php file can include a ultimate loop
$con = true;
while($con)
{
//do sample operation
if($end)
$con = false;
else
sleep(5); // 5 seconds for example
}
soloution 2 :
use cron jobs -- Depend on yout CP you can follow the instruction and call your php program at the specific times
limit : in cron job the minimum time between two calling is 1 minute
soloution 3 :
use a shell script and call your php program when ever you want
You can make PHP sleep for a certain amount of time - it will then resume the code afterwards but this is seriously not recommended because when a script sleeps it still uses up processor resources, and if you had multiple scripts sleeping for long periods of time it would put impossible load on your server.
The only other option that I know of is Cron. As #Pete says, you can manage Cron jobs from within PHP, e.g.:
http://net.tutsplus.com/tutorials/php/managing-cron-jobs-with-php-2/
This is going to involve a fair bit of coding, but I think it is your best options.
Another option is to have your user's browser call a PHP function using an Ajax request and JavaScript's setTimeout as suggested by the accepted answer in this question:
how to call a function in PHP after 10 seconds of the page load (Not using HTML)