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.
Related
I'm making a modification to the following code. I'm a newbie.
The code below is a short segment from a much longer code that scans a mySQL database every 5 minutes for specific events. The event below is triggered if a stock price exceeds a preset set value. Once the event is triggered a character string is constructed (called $body) and an email is sent.
The statement: "$body .=" makes sense to me and results in string of data that is eventually emailed.
The question is: where does the "print" statement print.
Is it going to a log. It is not appearing on my computer screen anywhere.
if (!empty($symbol_alert['alert_buy_stop']) && (float)$symbol_alert['alert_buy_stop'] < (float)$unique_symbol_data[$symbol_alert['symbol']]['price']) {
print "Price 'Buy Stop' triggered for symbol_id -> {$symbol_alert['id']} for user_id -> {$symbol_alert['user_id']}".PHP_EOL;
$body .=
'
Your BUY STOP price is: $'.number_format($symbol_alert['alert_buy_stop'],2);
$alerts_count++;
}
Assuming it's a linux server, it sounds like a cron job running the script every 5 minutes. The output is probably being redirected to a log file. Take a look at the user's crontab (the user which is running the script). At the end of the line there maybe a redirect >> /to/example/output.log
As the appropriate user, use crontab -e to view their cron jobs.
More on redirection here: http://www.tldp.org/LDP/abs/html/io-redirection.html
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 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.
Please don't laugh at me but I believe that I just did something extremely stupid. I was working on setting up a newsletter for a site that I am working on, but I tried it out at first when there was a typo. While scanning throughout the database and sending emails, I screwed up on the part that makes it stop. I fixed the code, but the emails are still being send (to my mom :O) and they don't seem to be stoping.
This is the script when I executed it:
$message = $_POST['emailmessage'];
$subject = $_POST['subject'];
$query = mysql_query("SELECT `email` FROM `members` WHERE `active`='1'");
//This line underneath should not be there
$rows = mysql_fetch_assoc($query);
$headers = array(
"From: contact#thestopitcampaign.com",
"Content-Type: text/html"
);
//should be '$rows = mysql_fetch_assoc($query)' instead of '$rows'
while($rows)
{
mail($rows['email'],$subject,$message,implode("\r\n",$headers));
echo "<p>Sent to: " . $rows['email'] . "</p>";
}
I contacted FatCow to see if they could stop the script, but they said that they could not do that and they would have to delete my entire account and put me on a different server. I cannot do that. Is there anyway to generate an error or something that would make the rogue script stop? FYI I do not have SSH access.
--I looked in my php config file and the timeout for a script is 300 seconds. That seems like a lot of emails to send. Is there anyway to stop those emails?
What has been sent can't be stopped any more. But it won't run forever and probably has already stopped.
If the server is not grossly misconfigured by the provider, your script didn't run any longer than a certain time limit, e.g. 60 seconds. Even though messages continue to come through, it's probably no longer running, but the mail server is taking its time to handle all the messages that it created.
I would wait and see - the flood is likely to end soon.
What the provider says about moving the account to a different server doesn't seem to make any sense at all - if there is a rogue process that is sending E-Mail, they should be able to kill it easily. But anyway... I would wait.
My guess is that the emails are just queued up and should eventually stop as php script wont keep executing itself after the page has stopped loading.
I'd suggest you to use a newsletter provider like mailchimp as they are more relyable, are safe and the service is easy to integrate in your website.
Hope that helps!
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.