I have a page that determines the variable ISSET and then acts on instructions. For example if the isset contains 'print' it loads a file via Include Template Path and echos a code on the bottom that prints the window.
eg.
if (isset($_GET['quoteprint'])) {
include(TEMPLATEPATH . '/bookings/booking-quote.php');
echo'<script type="text/javascript">window.print()</script>';
}
Now I would like a similar function to exist but this time to email the contents of that page to the user. I tired this but it does not work. I think the content needs to be converted but I don't know where to start.
else if (isset($_GET['quoteemail'])) {
$emailer = include(TEMPLATEPATH . '/bookings/booking-quote.php');
$to = $current_user->user_email;
$subject = "Your Quote - Dive The Gap" ;
$message = $emailer;
$headers = "From: Dive The Gap Bookings <ask#divethegap.com>" . "\r\n" .
"Content-type: text/html" . "\r\n";
mail($to, $subject, $message, $headers);
}
Any ideas?
Marvellous
The include function does not return the output or content of the script you're including.
See http://php.net/manual/en/function.include.php for more info (example #4 might be interesting for you).
You need to get the entire content of the page, or the part(s) you'd like to e-mail, into a variable. One way of doing this is using PHP's output buffering. A good explanation of how output buffering works can be found here: http://www.codewalkers.com/c/a/Miscellaneous/PHP-Output-Buffering/
Related
My question has differently been answered in another post, but I just can't make things work with my own code - so here it comes:
I am making a reminder function, that is supposed to be executed by cron job and send out an reminder email to remind client about an event.
I will use info from mysql, sort out the events that is going to be reminded based on X number of hours and the reminder time frame (if the cron job runs every 15 minutes, the code must find all event starting in the minutes between each cron job run).
All the above works just fine, and I do get the echo "test1"; from test-cron.php. But the email from test-cron-email-reminder.php is not send, and I do not get the echo "test2"; printed out.
I seems like my include in test-cron.php does not work. Why?
If I put it all together in one php file it works fine.
When this is ready, I will make a similar code to send out sms reminder with twilio. That as well works fine, as long as the whole code is in one file.
Both php files are in the same folder.
Here is my code:
TEST-CRON.PHP
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// Get info from SQL
$result = performQuery("SELECT mindful_pbbooking_events.service_id,
mindful_pbbooking_treatments.id,
mindful_pbbooking_events.id, name,
customfields_data,
dtstart, dtend, date_created
FROM mindful_pbbooking_events,
mindful_pbbooking_treatments
WHERE
mindful_pbbooking_events.service_id=mindful_pbbooking_treatments.id;
");
while ($row = mysqli_fetch_array($result)) {
//Split customfields_data and collect the informaton from created array (just making things a little bit more easy to work with)
$dataArray = $row[customfields_data];
$dataArrayDecoded = json_decode($dataArray,TRUE);
$clientFname = $dataArrayDecoded[0][data];
$clientLname = $dataArrayDecoded[1][data];
$clientEmail = $dataArrayDecoded[2][data];
$clientMobile = $dataArrayDecoded[3][data];
$clientGender = $dataArrayDecoded[4][data];
//Collect information from customfields_data (more making things a little bit more easy to work with)
$eventId = $row[mindful_pbbooking_events.id];
$eventStart = $row[dtstart];
$eventDate = date("Y-m-d", strtotime($eventStart));
$eventTime = date("H:i", strtotime($eventStart));
$eventEnd = $row[dtend];
$service = $row[name];
$eventCreated = $row[date_created];
//Time calculation to find out who to send reminder to
$eventtimestring = strtotime("$eventStart");
$nowtimestring = strtotime("now");
$reminderdurationstring = $reminderDuration*60;
$startstring = $nowtimestring + $hours*3600;
$endstring = $startstring + $reminderdurationstring;
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
// ****** HERE IT COMES ******
// The test-cron-email-reminder.php is the file with the code I want to include
include 'test-cron-email-reminder.php';
}
}
?>
TEST-CRON-EMAIL-REMINDER-PHP
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// Just a little test to find out where things goes wrong
echo "test2";
$to = "$clientEmail";
$subject = "The reminder mail body";
$message = "
<html>
<head>
<title>The reminder mail title</title>
</head>
<body>
<p>The reminder mail body</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: $clientFname <$clientEmail>';
$headers[] = 'From: Mindful <mail#mail.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
break;
?>
require 'configuration.php';
in TEST-CRON-EMAIL-REMINDER-PHP
may produce redeclaration error
try require_once 'configuration.php';
to prevent it
The problem is in TEST-CRON.PHP -- don't put an include inside a while loop, unless you really want to include that file over and over. (You don't)
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
...
/// DON'T DO THIS
include 'test-cron-email-reminder.php';
/// DON'T DO THIS
}
Instead, do this. In TEST-CRON.PHP:
<?php
require_once 'Connect_db.php';
require 'configuration.php';
require_once 'TEST-CRON-EMAIL-REMINDER-PHP'
...
while (($startstring <= $eventtimestring) && ($eventtimestring < $endstring)) {
// Just a little test to find out where things goes wrong
echo "test1";
...
doSomething(); // Defined in TEST-CRON-EMAIL-REMINDER-PHP
break;
}
In TEST-CRON-EMAIL-REMINDER-PHP:
<?php
require_once 'Connect_db.php';
require 'configuration.php';
// And wrap all this stuff up in a function that
// you can call from within your while() loop.
func doSomething() {
// Just a little test to find out where things goes wrong
echo "test2";
$to = "$clientEmail";
$subject = "The reminder mail body";
$message = "
<html>
<head>
<title>The reminder mail title</title>
</head>
<body>
<p>The reminder mail body</p>
</body>
</html>
";
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'To: $clientFname <$clientEmail>';
$headers[] = 'From: Mindful <mail#mail.com>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
}
?>
I am working with a mail. What I exactly want is the page should be redirected to the universal resource locator after 5 seconds. The header line is working fine in all other files but not in this file. I tried my best to find what is wrong. The before and after line is also working fine but the page is not redirecting. And even I have checked the code many time and there is no error.
Can you please tell me the reason why is it happening?
Code
<?php
if (isset($_POST['fullname']) && isset($_POST['email']) && isset($_POST['message']) && isset($_POST['submit'])) {
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "ziajappa1#gmail.com";
$subject = "Customer";
$txt = "Hi, Grand4Love ".$fullname." have contacted you. Do hurry to contact him back! The user's email address is: ".$email."";
$headers = "From: client#perfecttips.com\r\n";
//."CC: somebodyelse#example.com";
if(mail($to,$subject,$txt,$headers)){
echo "<h2>Thank you for contacting us, we will respond to your message withing 24 hrs<h2>";
}
header('refresh:5; url=http://perfecttips.co/');
// The above line is working in the other files but not here.
// Please suggest me why the above line is not working?
echo "hi";
}
?>
Is there anything that is included in this file that is written to the response before the header is parsed?
Headers need to be the first thing that page parses, or else it will be ignored.
Look for echoes or something in previously imported files.
Edit:Yup. You are echoing. Comment out all echoes and you'll see it should work.
So, I have this piece of text that I would like to come from elsewhere to inside a function. I put it in "configuration.php" and would like to use in a file "functions.php"
configuration.php
$event_confirmation_message = "Your awesome submission has been approved - $link. ";
functions.php
somefunction(several arguments go here){
//code that does other stuff with the function arguments
//then we need to send the confirmation message
global $event_confirmation_message; //to change, see configuration.php
$link = "http://www." . $city . "events.info/index.php?option=events&main_id=" . $row['main_id'];
mail($email, "Please check your your submission", $event_confirmation_message, "From: contact#me.info");
}
It all works, the mail is sent, the confirmation message arrives, but $link in the email that is sent is blank (empty, non-defined?). So the local variable $link somehow does not get processed within the global variable $event_confirmation_message. Is there something I am doing wrong?
Do like this:
// configuration.php
$event_confirmation_message = "Your awesome submission has been approved - ";
//functions.php
somefunction(several arguments go here){
global $event_confirmation_message;
$link = "http://www." . $city . "events.info/index.php?option=events&main_id=" . $row['main_id'];
$msg = $event_confirmation_message . $link;
mail($email, "Please check your your submission", $msg, "From: contact#me.info");
}
PHP cannot time travel.
$link in your configuration.php will be evaluated/replaced when configuration.php is parsed/loaded. Therefore your $event_confirmation_message will NOT contain a variable anymore when you use the variable elsewhere. It'll contain whatever text was in $link at the time $event... was defined.
This is very much like buying a cake at the store, and wondering why you can't find the egg/flour/milk/sugar that it's made of - all of that was "destroyed" in the bakery and you have just cake...
I am using EFUMultiple Uploader to receive files on my site. Does anyone know of a tutorial that will teach me how I can be notified each time there is a new file or batch of files in my uploads folder?
It will become annoying, fast, I can promise you that.
But either way, in your upload script, you'll want to use either the mail() function or, for example the PHPMailer library if you don't have a SMTP server configured on your PHP installation.
Consider this (untested) script:
#!/usr/bin/env php
<?php
// Warning: this script and UPLOADED_FILES_DB, for security reasons, should not be in UPLOAD_PATH.
define('UPLOAD_PATH', '...');
define('UPLOADED_FILES_DB', 'uploaded_files');
define('MAIL_TO', 'you#example.com');
define('MAIL_FROM', 'cron#example.com');
define('MAIL_SUBJECT', 'Uploaded files');
// Get old files:
if (file_exists(UPLOADED_FILES_DB)) {
$old_files = unserialize(file_get_contents(UPLOADED_FILES_DB));
} else {
$old_files = array();
}
// Get current files:
$current_files = array();
foreach (new DirectoryIterator(UPLOAD_PATH) as $file_info) {
if (!$file_info->isDot()) {
$current_files[$file_info->getFilename()] = filemtime($file_info->getFilename());
}
}
// Update database:
file_put_contents(serialize($current_files), UPLOADED_FILES_DB);
// Compute differences:
$added_files = array_diff(array_keys($old_files), array_keys($current_files));
$removed_files = array_diff(array_keys($current_files), array_keys($old_files));
$changed_files = array_diff_assoc($old_files, $current_files);
// Send message:
$headers = 'From: ' . MAIL_FROM . "\r\n";
$message = 'Added files: ' . implode(', ', $added_files);
mail($to, $subject, $message, $headers);
Then you would put that script on a cron job to execute every day or so, or you can include it in wherever your upload code is — though, the latter approach would get annoying quickly.
Im using the php mail function to send a link with many many paramaters. The url after being encoded can be 650 or more characters long because its holding variables to repopulate a form.
When I click on the link in my email its broken because a space has been inserted somewhere in the URL.
Heres my sendMail function:
protected function sendEmail($to, $subject, $body) {
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . '\r\n';
$headers .= 'From: Sales Order From <sales#imninjas.com>' . '\r\n';
$headers .= 'X-Mailer: PHP/' . phpversion() . '\r\n';
$body = '<html><body style="font-size: 10pt; font-family: Arial, Helvetica, sans-serif;">'.$body.'</body></html>';
return mail($to, $subject, $body, $headers);
}
Heres the code I call sendMail with. Its the '$salesUrl = $this->getSalesFormUrl();' that is the 650+ character url chock full of encoded paramaters.
function emailRep() {
$params = $this->getParamaterArray();
$shortUrl = $this->getShortUrl();
$salesUrl = $this->getSalesFormUrl();
$mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";
$mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
$mailBody .= "Customer Contact Information:<br/>";
$mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
$mailBody .= "Shortened Url to Send to the Customer:<br/>";
$mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
$mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
$mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
$mailBody .= "<a href='".$salesUrl."'>".$salesUrl."</a><br/><br/>";
return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}
And here's the URL I receive in my email, you'll notice the space '...BhsNKq Jsd_x4...' in the middle of the URL. This happens in a different place each time even if I'm sending the exact same url. To prove this I hard coded this url without a space in the emailRep method and sent it multiple times. The space moved around.
http://example.com/admin/index.php?fdJdj9QgFAbgXzPcNJ3AAdbxgotxdk28cNRMjPESW9yihVbKxHR_vaeU7TSZxqSfHDhPX9Jg-lPneu1H9cFHE7yJxUcdfpto_XNxtv6XHkgw_Vk7oy7aFRdnYzONPDltWxV01Zi23glqnU-z91XnpvrnpvNGSXYo4Q0t6UEKUmUp9Sh28JC7Va01Pmaibcc83M8dpCzzKYn5H_rX_BhsNKq Jsd_x4w7e4zHqputSWdc1Uwzezt2LS5xGQJHKxlF98qbzUZMhauxw_k5ebK8YPwDFr776GEb11WPzGtfhjIFE68zL9H2l3FOCFXea5qkHUmO9pCihThlegDLAHamuIeCmTiXSGv8cm_TorL-6q8NnYuvp6nEfpntthgrvx3enkhWP-FJ0P4vYYAvyJ45pbR9slaw9pbPLsnu4d9nNZSuXJZdll2WXJRc2XKYgu0zRvcwuqBSVwuzylQu4ILugxOJCciG7kF1Qx8vjZl5Y8sIqL59dRu9dfnP5yuXJ5dnl2eXJ3crLl7x8lVeoFJWKe1co_uoK_B1eXZFckV2RXaG-fHvazCuWvGKVV84u23DlzZUrVyZXZldmVyZ3K69c8so57z8
Here is the code I use to encode / decode the url paramaters before sending it through the email.
class UrlEncoder {
function compressUrl($url) {
return rtrim(strtr(base64_encode(gzdeflate($url, 9)), '+/', '-_'), '=');
}
function uncompressUrl($url) {
$startParams = strrpos($url, "?");
if($startParams) {
$paramaterString = substr($url, $startParams);
$host = substr($url, 0, strrpos($url, "?"));
$uncompressedParamaters = gzinflate(base64_decode(strtr($paramaterString, '-_', '+/')));
return $host."?".$uncompressedParamaters;
} else {
return NULL;
}
}
}
How do I prevent this space? I know I could shorten the URL with something like bit.ly however its an internal tool. I feel like there must be a way to stop the space from being inserted.
Who in their right mind uses a 650-character long query string?
My recommendation is to save the query-string server-side. Put it in a database with an AUTO_INCREMENT field, then you can get an ID for it. Then you can just send the URL as http://example.com/?email_key=ID_GOES_HERE, a much shorter URL. Then just look up the query string from the database.
Done.
I have what you need, http://www.9lessons.info/2009/01/split-url-from-sentence-using-php.html. Create tinyurl links using API,nothing in the database :)
Ok,I had same issue. My solution was my own link shrinking... Make new table in database with few rows, few lines of code in your old script, and new page for redirect... This is shortest explanation, if you need some help,just ask :)
EDIT:
function emailRep() {
$params = $this->getParamaterArray();
$shortUrl = $this->getShortUrl();
$salesUrl = $this->getSalesFormUrl();
/***********************************************************************************/
$arr = str_split('QWERTYUIOPLKJHGFDSAZXCVBNM123456789qwertyuioplkjhgfdsazxcvbnm'); // get all the characters into an array
shuffle($arr); // randomize the array
$arr = array_slice($arr, 0, 6); // get the first six (random) characters out
$short = implode('', $arr); // smush them back into a string
mysql_query("INSERT INTO shortlinks VALUES(NULL, '$salesUrl', '$short')");
/*******************************************************************************************/
$mailSubject = "Return to the sales order form for ".$params['clientName']." at ".$params['company'].".";
$mailBody = "The following information is from an order created on, ".date("l, F j, Y \a\t g:i a").",<br/><br/>";
$mailBody .= "Customer Contact Information:<br/>";
$mailBody .= "Name: ".$params['clientName'] params['company']."<br/>";
$mailBody .= "Shortened Url to Send to the Customer:<br/>";
$mailBody .= ($shortUrl) ? "<a href='".$shortUrl."'>".$shortUrl."</a><br/><br/>" : "There was an error shortening your url.<br/><br/>";
$mailBody .= "The URL back to the sales form: For sales rep use only, <strong>Do not give to the customer</strong>.:<br/>";
$mailBody .= "<span style='font-style: italic;'>Some email clients add special characters to long urls. If the link does not work then copy and paste it into your browser.</span><br/>";
$mailBody .= "<a href='".$short."'>".$short."</a><br/><br/>"; // Rename $salesUrl to $short
return ($this->sendEmail($params['repEmail'], $mailSubject, $mailBody));
}
And redirect page:
$token=$_GET['token']; // like http://example.com/out.php?token=ahgByT or make it cleaner with htaccess
$qry=mysql_query("SELECT * FROM links WHERE short='$token'");
$arr=mysql_fetch_array($qry);
$out=$arr['long_link'];
header("Location: ".$out);
?>