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.
Related
I want to let my server send me e-mails with birthday reminders based on a birthday calendar in a database on the server at my web hosting provider's. I know how to send e-mails from PHP, but only as an action after a button click on the client side. That's also the only way to perform an action I could find.
How can I have my server send me an e-mail on a specific date/time without user interaction?
edit
I don't think my question is a duplicate. The presumed duplicate link refers to a question about cron, and the answer is about the syntax, but it doesn't explain how cron works, or how I can use it for my problem.
You can write a php script for execution on the command line. To run a php script from the command line you just use the php command:
php myscript.php
In this example if myscript.php has all the logic to send your emails, then you just setup a cron job to execute the file automatically ever day, or every hour (however often you would like it to execute). Then all you need to do is write the logic in your PHP script to check if its "time" to send one of those emails.
The answer on this post has a great explanation of setting up cron jobs for php scripts.
To elaborate on the comment given by Apb;
create your php file with the contents (the script part the button)
Use cron for linux os or if you're on windows to execute you're php script
Another option is setcronjob.com answered by Santosh Achari on enter link description here question
As other said cronjobs are a good way to achieve this.
For example (very rudimental) script.php
include '../connect.php';
$birthday_list =[];
$today = date("m.d.y");
try {
$sql = "SELECT `Birthday`, `Name`, `Surname`, FROM `Friends` WHERE Friends.Birthday = '$today'";
foreach ($conn->query($sql) as $row) {
$temp = [$row['Birthday'],$row['Name'],$row['Surname']];
$birthday_list[] = $temp;
}
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
foreach ($birthday_list as $el){
$name = $el[1];
$surname = $el[2];
$message = 'Todays is'.$name.' '.$surname.' birthday';
mail('me#example.com', 'My Subject', $message);
}
Then you can run this script as cronjob, some hostings (godaddy for example) allow you to set crons from cpanel, otherwise you have to set crons from your server shell.
I have a PHP script which ends with a header redirect, I want to schedule it via a Cron Job.
Reading around took me to the 'lynx' library that I thought was essentially a browser-lite way of doing a Cron Job that would act in the same way as a browser and be able to execute my redirect.
A simplified version of my script looks like:
<?php
// Connect to DB
require_once($_SERVER['DOCUMENT_ROOT']."/admin/inc/dbconnect.php");
// Check DB for quotes that have not been sent to this client
$query_quotes = "SELECT * FROM quotes WHERE sent_client = 0 LIMIT 1";
$view_request = mysqli_query($GLOBALS['db_connect'], $query_quotes);
// Send to external system and email customer with quote
while ($quotes = mysqli_fetch_array($view_request)){
$Body = "Email Content";
// Send email via Swift Mailer
// Send quote information to third party system via URL redirect
header('Location: http://exampleurl/?FirstName='.rawurlencode($quotes['name']).'&businessName='.rawurlencode($quotes['company_name']).'.');
}
?>
It finds records in my database then sends the customer an email before compiling a URL with their information and redirecting to it. The variables in the URL are then read by a third party system and inputted into their database.
I'm activating the cron job (via Plesk scheduler) like so:
/usr/bin/lynx -source http://exampleurl2/script.php > /dev/null
I know the script is being executed but the redirect part is not working still, am I doing something wrong with lynx? Also tried recreating the redirect function with cURL but couldn't seem to do so.
I customized a calendar plugin which shows today's birthdays and current months list of wedding anniversaries in the home page of the site. i wrote a code in that plguin's displaying page using wp_mail and mail will send. but this happens only when the site is visited. my code:
if($dat==date('Y-m-d'))/*$dat is the date of event from DB*/
{
if($eid!=''){ /*if recipient email id is not null*/
if($se!=1) /*if email is sending first time then($se=db column 'send'value) $se=0 otherwise it is 1*/
{
$to=$eid;
$sub="Birthday Wishes";
$msg='Happy Birthday '.$ev_title[$j];
$headers= 'From:Mysite <noreply#mysite.com>' . "\r\n".'Content-type: text/html';
$attachments=array(WP_CONTENT_DIR . '/plugins/spider-event-calendar/images/happybday.gif');
$rx=wp_mail($to,$sub,$msg,$headers,$attachments);
$wpdb->update($wpdb->prefix. "spidercalendar_event",array('send'=>1),array('id'=>$ev_id[$j]));/**/
//echo "email send";
}
else{
//echo "email already sent";
}
}
}
i heard about wp_cron but when i searched in this forum about how to write cron in wordpress i saw an answer like
Unfortunately the WordPress cron jobs are only triggered when your site is visited
if it is true then how can i send emails daily even without visiting the webpage.is there any other way for this?
You can set up a regular cron job using your terminal via the following process after logging in;
access your con jobs list using;
crontab -e
There will likely be some lines in there already. Type o to enable editing of the file;
You can use the following website to generate the command for it to issue http://www.corntab.com/pages/crontab-gui.
as an example job I've got on my server;
*/5 * * * * /usr/bin/php -q /var/www/www.mysite.com/cron.php >/dev/null 2>&1
This job runs a php script every 5 minutes and prevents the site admin from receiving an email every time it runs. That's what 2>&1 does at the end of the line.
I'm actually a little unsure what /usr/bin/php -q and >/dev/null do, as I just copied them from another job that was already set up in that way. I'm fairly new to this via command line.
Once you're done editing the job, press esc and then Shift + zz to exit out of it. And you should be done.
I'd recommend using a test script that emails yourself, to make sure it works correctly first, then change it to use the script you're trying to run once you know it works.
I don't know if this process would be different for different server set ups, but it might be. This is just what I have to do for my server which runs CentOS with apache.
I'm tearing my hair trying to figure out why this could possibly not work when it works when executing from the command line. I'm sending a POV-Ray animation to the user after it is done rendering and compiling the frames into a GIF using ImageMagick. I have the email that is sent through mutt sleep for an hour so that it allows time for the user animation to be compiled. (I've changed it to 120 seconds however so that I don't have to wait an hour to troubleshoot. In that respect I also made the animation only have 3 frames until I figure out the issue.)
A new bash file, animation_done_bash.sh, is created each time a user clicks animate on my site which in turn creates a new folder that stores the frames for the animation and with animation_done_bash.sh in it. To make the PHP page advance to the next page the bash file is executed in dev null. I already tested if that was the problem on the command line and it works there so I really have no idea what is the issue.
Below is the code and the output (I echoed this out onto my php page to see what was wrong) that is produced that is being executed with shell_exec:
$animation_done_email = "#!/usr/bin/bash \nsleep 120; mutt -s \"Animation Finished\" -a animation.gif -- ".$email." <email.txt;";
/*Creates new animation_done_bash each time user hits animate*/
$directory_bash = "./User_Files/Animation/".$location."/";
$filename_bash = 'animation_done_bash.sh';
$handler_bash = fopen($directory_bash.$filename_bash, "w");
fwrite($handler_bash, $animation_done_email);
fclose($handler_bash);
/*Need to change the permissions on bash file so it can execute*/
chmod($directory_bash."/animation_done_bash.sh", 0777);
$command_5 = 'cd /home/ouraccount/public_html/User_Files/Animation/'.$location.'/; bash animation_done_bash.sh > /dev/null 2>/dev/null &';
$shellOutput = shell_exec($command_5);
Where $email is the user's email and $location is the folder in which the frames are stored. email.txt is stored within the same folder.
Output:
cd /home/ouraccount/public_html/User_Files/Animation/ani_51/; bash animation_done_bash.sh > /dev/null 2>/dev/null &
Any guidance would be much appreciated. Thanks!
In this kind of situations pushing (invoking a script when the rendering operation is complete) is preferrable to polling (periodically checking if the rendering operation is complete).
If you cannot push, do it in one language only, don't create a hybrid of bash and PHP.
Here is are 2 examples you could try which might suit your situation:
Example if rendering command returns after finishing:
<?php
/** PHP wrapper around rendering command X that mails the output **/
// Don't write attachment code yourself, use a class like PHPMailer: https://github.com/Synchro/PHPMailer
require_once('class.phpmailer.php');
// Ignore user browser close, rendering takes a long time
ignore_user_abort(true);
// On windows you'll also need to set_time_limit to something large. On Unix PHP doesn't count things like database queries and shell commands, on Windows it does
// Execute render command, don't forget to escape if you use user input
// Script will only continue once renderer returns. If renderer return before rendering is finished you cannot use this
$render_output = shell_exec('renderer input.file output.file');
// Could also be done in PHP for finer control and error handling
$imagemagick_output = shell_exec("convert output.file animation.gif");
unlink("output.file");
$mail = new PHPMailer();
$mail->addAttachment('animation.gif');
// etc.
unlink("animation.gif");
?>
Example if rendering command returns before finishing:
<?php
/** PHP wrapper around rendering command X that mails the output **/
// Don't write attachment code yourself, use a class like PHPMailer: https://github.com/Synchro/PHPMailer
require_once('class.phpmailer.php');
// Ignore user browser close
ignore_user_abort(true);
// Execute render command, don't forget to escape if you use user input
// If renderer returns before file is finished use this
$render_output = shell_exec('renderer input.file output.file 2> error.file');
// Wait for rendering to finish
// Implement these function, e.g. file_exists for output.file or error.file
while(!rendering_has_failed() && !rendering_is_finished()) {
sleep(15*60); // Low-resource wait for 15 minutes
}
// Could also be done in PHP for finer control and error handling
$imagemagick_output = shell_exec("convert output.file animation.gif");
unlink("output.file");
$mail = new PHPMailer();
$mail->addAttachment('animation.gif');
// etc.
unlink("animation.gif");
?>
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)