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.
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 have a php script that is currently invoked directly by a webhook. The webhook method was fine up until this past week where the volume of requests is becoming problematic for API rate limits.
What I have been trying to do is make a second PHP file ($path/webhook-receiver.php) to be invoked by webhooks only when there isn't a process running. I'll be using the process user webb recommended, which is in the invoked script ($path/event-finance-reporting.php) it will create a file as the first action, and the delete that file as the last exection.
Before invoking the script the automation will check the directory to make sure it is empty, otherwise it will kick back an error to the user telling them to wait until the current job is completed before submitting another one.
The problem I'm running into now is that both $command1 and $command2'. both end up invoking the$path/webhook-reciever.phpinstead of$path/event-finance-reporting.php`.
$command1 = "php -f $path/event-finance-reporting.php 123456789";
$command2 = "/usr/bin/php -q -f $path/event-finance-reporting.php 123456789";
Anyone know why would be?
The goal it to have only one instance of event-finance-reporting.php run at a time. One strategy is to create a unique lockfile, don't run if it exists, and delete it when it finishes, e.g.,:
$lockfilepath = '.../event-finance-reporting.lock';
if(file_exists($lockfilepath)){
print("try again later");
exit();
}
touch($lockfilepath);
...
// event-finance-reporting.php code
...
unlink($lockfilepath);
You could also do something more complicated in the if, such as checking the age of the lockfile, then deleting and ignoring it if it was left behind awhile ago by a crashed instance of event-finance-reporting.php.
With this strategy, you also don't need two separate phps.
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 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.