I'm using PHP for sending an e-mail. The values in the e-mail are depending on the inputs of a form. But for some reason, the mail is suddenly not sending. It did before. What's wrong with my code?
Orders are placed correctly in the database, so no error there.
if ($order->addOrder($_DB)) {
$user = "SafetyCam.be";
$verzonden = FALSE;
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$zip = $_POST['zip'];
$place = $_POST['place'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$twogig = $_POST['vn_qty'];
$fourgig = $_POST['ja_qty'];
$total = $_POST['total'];
$totaal = (($twogig * 50) + ($fourgig *80) + 2.5);
$headers = 'From: info#something.be';
$to = 'me#gmail.com';
$subject = 'Bevestiging bestelling';
$message = 'Hello $firstname,
You placed the following order on our website.
- $twogig x 2GB SafetyCams ordered
- $fourgig x 4GB SafetyCams ordered
+ shippingcosts (2,5 EUR)
The total cost for this order amounts to $totaal EUR.
Your products will be delivered as quickly as possible after receipt of your payment.
Please transfer the order amount of $totaal EUR into account X.
After payment, the products will be sent to the following address:
$firstname $lastname
$address
$zip $place
$country
We hope you will be very happy with your purchase.
Sincerely yours";
if (mail($to, $subject, $message, $headers)) {
$verzonden = TRUE;
$feedback = '<div class="feedbackheader">Thanks</div><br / >';
} else {
$verzonden = FALSE;
$feedback = '<div class="feedbackheader">Error!</div>'; }
}
else {
$feedback = '<div class="feedbackheader">Error!</div>';
}
}
Why do you open your mail $message with a single quote and end it in a double quote.
You should open and end with both double quotes, especially since you use PHP variables inside.
$message = 'Hello $firstname"; //Wrong
$message = "Hello $firstname"; // Works
You've opened the "message" string with an apostrophe ' but tried to close it with a quotation mark ". The SO syntax highlighter gives it away!
You have started your variable $message = 'Hello $firstname, with single quote and end it with double quote, what you need to do is just make
$message = "Hello $firstname
if you put it in single quote php wont scan your variable content for varible like $firstname
Your $message variable starts the string with a ' but ends it with a ", so all the code after it is included in the variable until another ' which happens when your defining $feedback.
Basically you are not closing the string, and therefore your entire code is being changed. If you are using color coding you should have seen this (I can see it from your question).
Also, if you are using single quotes, you cannot use inline variables.
$var = 1;
echo '$var'; // ouput: $var;
echo "$var"; // output: 1
You start your message-string with a single quote (') and try to end it with a double quote, thus your logic is parsed incorrectly.
I use SwiftMailer:
require_once('../lib/swiftMailer/lib/swift_required.php');
function sendEmail(){
//Sendmail
$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
//Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
$body="Dear $fname,\n\nYour job application was successful. \n\nYours,\n\nEamorr\n\n\n\n\n\n\n";
//Create a message
$message = Swift_Message::newInstance('Subject goes here')
->setFrom(array($email => "no-reply#yourdomain.com"))
->setTo(array($email => "$fname $lname"))
->setBody($body);
//Send the message
$result = $mailer->send($message);
}
Related
I've successfully created a multi page php form that uploads all the data to a mysql database. Now I'm trying to get this mail function to work with it, so we can get an email each time someone successfully completes the form.
I'm getting the email now but not the information from the form.
I'm not sure what I'm doing wrong, I'm guessing it's something to do with SESSION but I'm having a hard time actually finding a solution.
Here's the code I'm working with:
<?php
session_start();
foreach ($_POST as $key => $value) {
$_SESSION['post'][$key] = $value;
}
extract($_SESSION['post']); // Function to extract array
$connection = mysql_connect("mysql.database.com", "r-----a", "An-----1!");
$db = mysql_select_db("---------", $connection); // Storing values in database.
$query = mysql_query("insert into detail (whenadded,yourname,reservationid,reservationname,property,eta,cellphone,email,signature,petcontract) values(Now(),'$yourname','$reservationid','$reservationname','$property','$eta','$cellphone','$email','$signature','$petcontract')", $connection);
/* Set e-mail recipient */
$myemail = "blahblahblah#retreatia.com";
$yourname = ($_POST['yourname']);
$reservationid = ($_POST['reservationid']);
$reservationname = ($_POST['reservationname']);
$property = ($_POST['property']);
$eta = ($_POST['eta']);
$cellphone = ($_POST['cellphone']);
$email = ($_POST['email']);
$petcontract = ($_POST['petcontract']);
/* Let's prepare the message for the e-mail */
$subject = "$yourname has checked in using Express Checkin!";
$message = "
Information of Express Checkin User:
Name: $yourname
Reservation ID: $reservationid
Name on Reservation: $reservationname
Property: $property
Cell Phone: $cellphone
Email: $email
ETA: $eta
Pet Contract: $petcontract
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
if ($query) {
echo '<div class="absolutecenter boxshadows"><img src="../img/thankyoupage.png" class="img-responsive"></div>';
} else {
echo '<p><span>Form Submission Failed!</span></p>';
}
unset($_SESSION['post']); // Destroying session
?>
Also the form is populating all fields in the database successfully and produces the img file from the echo...
Since you did this:
extract($_SESSION['post']); // Function to extract array.
... this block is unnecessary:
$yourname = ($_POST['yourname']);
$reservationid = ($_POST['reservationid']);
$reservationname = ($_POST['reservationname']);
$property = ($_POST['property']);
$eta = ($_POST['eta']);
$cellphone = ($_POST['cellphone']);
$email = ($_POST['email']);
$petcontract = ($_POST['petcontract']);
In fact, it's probably why your variables aren't populating. They're getting overwritten with empty values since $_POST doesn't contain values from previous pages.
I have tried both real escape string and other php methods but I am not sure I am using them correctly. This code shows my input and then the ajax post, where and how would I preform the sanitation?
Please note there is no data base connection so all the character stripping would have to be done in jQuery somehow.
Would this be more of the correct direction to go in?
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$msg = "
Name:$name
Email:$email
Phone:$phone
Comment:
$message";
function checkInput($msg) {
$msg = #strip_tags($msg);
$msg = #stripslashes($msg);
$invalid_characters = array("$", "%", "#", "<", ">", "|");
$msg = str_replace($invalid_characters, "", $msg);
return $msg;
}
$to = "email address";
$subject = "name";
$message = $msg;
$headers = "Contact form enquiry";
mail($to,$subject,$message,$headers);
?>
You perform sanitation immediately before you put the text into some code or specific data format.
So in the code you have here:
var dataString = 'name=' + name + '&email=' + email + '&phone=' + phone + '&message=' + message;
You would escape each variable before you put it into the URL. You can do that with encodeURIComponent. However, you are using jQuery ajax so you shouldn't be doing that by hand in the first place.
data: { 'name': name, 'email': email, 'phone': phone, 'message': message},
And in the HTML you are generating:
.append("<h2 class='text-center form_submit_text'>Hi " + name + ", we will contact you soon </p>")
should be:
var heading = jQuery("<h2>").addClass('text-center').addClass('form_submit_text').text("Hi " + name + ", we will contact you soon);
$('#thanks').empty().append(heading);
You might also need to do some escaping in your PHP, such as before putting data into SQL.
You validate and sanitize in bin/mail.php. See filter_var for the built in ways to validate and sanitize incoming data. For example, for email you can do
if (filter_var($_POST['email']), FILTER_VALIDATE_EMAIL)) {
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL));
}
Phone numbers would required a regular expression to validate and sanitize (so it only contains numbers and/or re-formats to your preferred format). Free text like $message should use FILTER_SANITIZE_STRING.
I would like to know how to pass form data from a php processing page to a success page.
How can I pass the $orderid to my success page? I only need to pass this one value so something simple would be great! :-P
<?php
$stamp = date("Ymdhis");
$random_id_length = 6;
$rndid = generateRandomString( $random_id_length );
$orderid = $stamp ."-". $rndid;
function generateRandomString($length = 10) {
$characters = '0123456789';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$repairtitle = $_POST['courierrepairtitle'];
$repairconsole = $_POST['courierrepairconsole'];
$repairprice = $_POST['courierrepairprice'];
$outwardpostage = $_POST['outwardpostage'];
$returnpostage = $_POST['returnpostage'];
$name = $_POST['couriername'];
$email = $_POST['courieremail'];
$homephone = $_POST['courierhomephone'];
$mobilephone = $_POST['couriermobilephone'];
$address1 = $_POST['courieraddress1'];
$address2 = $_POST['courieraddress2'];
$address3 = $_POST['courieraddress3'];
$city = $_POST['couriercity'];
$county = $_POST['couriercounty'];
$postcode = $_POST['courierpostcode'];
$country = $_POST['couriercountry'];
$formcontent=" Order No: $orderid \n \n Repair Title: $repairtitle \n Console: $repairconsole \n Price: $repairprice \n \n Outward Postage: $outwardpostage \n Return Postage: $returnpostage \n \n Name: $name \n Email: $email \n Home Phone: $homephone \n Mobile Phone: $mobilephone \n \n Address1: $address1 \n Address2: $address2 \n Address3: $address3 \n City: $city \n County: $county \n Postcode: $postcode \n Country: $country ";
$recipient = "info#example.co.uk";
$subject = "Order Form";
$mailheader = "From: $email \r\n";
// Test to see if variables are empty:
if(!empty($name) && !empty($email) && !empty($homephone) && !empty($address1) && !empty($city) && !empty($postcode) && !empty($country)){
// Test to see if the mail sends successfully:
if(mail($recipient, $subject, $formcontent, $mailheader)){
header("Location: http://www.example.co.uk/courier-mailer-success.htm");
}else{
header("Location: http://www.example.co.uk/courier-mailer-fail.htm");
}
}else{
header("Location: http://www.example.co.uk/courier-mailer-fail.htm");
}
exit;
?>
You could place it at the end of the URL as a GET parameter.
'success.php?orderid=one'
on that page access it with:
$_GET['item']
You could Store your data in a session and access it from your success page
A session variable would work great in this case. These are used to persist data between pages, and this gives the benefit of being able to access this variable throughout your application without having to pass as a GET parameter for every page where necessary. At the very top of your file, you'll need to start your session:
<?php
session_start();
$stamp = date("Ymdhis");
...
From here, you now have access to assign a session variable. the code will be as follows:
if(mail($recipient, $subject, $formcontent, $mailheader)){
$_SESSION['orderid'] = $orderid;
header("Location: http://www.example.co.uk/courier-mailer-success.htm");
}
From here, redirect to your success page. You will need to make your courier-mailer-success.htm into a .php file in order to access this data. You'll also need to add session_start(); to the top of your success page to access the session data. You can access your variable like so:
<?php
session_start();
...
$id = $_SESSION['orderid'];
echo $id;
I've created a static website (clients request) and we have put a email form inside the contacts page. the form works well and sends the data but in the email that is received i get
sam\'s clover\'s (Test Data) how to cleans the data in a static website to remove the \'s and just leave it as 's in the email.
I've tried looking with my keywords not really finding any luck based on the static parts.
any help would be great thanks
This is the vars i'm using at the moment.
$to = STRIP_TAGS($_POST['remail']);
$from = STRIP_TAGS($_POST['semail']);
$phone = STRIP_TAGS($_POST['sphone']);
$subject = STRIP_TAGS($_POST['subject']);
$message = STRIP_TAGS($_POST['message']);
$headers = "From:" . $from;
Use stripslashes():
It unquotes a quoted string. So \' becomes '.
$to = stripslashes($_POST['remail']);
$from = stripslashes($_POST['semail']);
$phone = stripslashes($_POST['sphone']);
$subject = stripslashes($_POST['subject']);
$message = stripslashes($_POST['message']);
$headers = "From:" . $from;
You can also use it for arrays:
stripslashes_deep($array_name);
Read about it here: http://php.net/manual/en/function.stripslashes.php
What your after is stripslashes(), but if slashes are being added by PHP automatically from magic quotes then you should check for that, this way your script will run on any server, not just a server with magic quotes on.
Here is a callback function that will loop through all the effected Global vars and fix. You would add this as part of your initialization.
<?php
function process_gpc(&$value, $key){
//magic quotes fix
if (get_magic_quotes_gpc()) {
$key = stripslashes($key);
$value = stripslashes($value);
}
//null byte (string termination) protection
$key = str_replace(chr(0), '', $key);
$value = str_replace(chr(0), '', $value);
}
$inputs = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST, &$_FILES);
array_walk_recursive($inputs, 'process_gpc');
?>
Hi I am wondering if someone could take a look at my code and see what error there is as I cant see any. what is happening is that it is not saving the emails I am sending it to the mysql, and instead I get a bounced email back.
When I run PHP test to see if it saves to the mysql table, it does not.
I have taken out the connect code as it has my username and password.
#!/usr/bin/php -q
<?php
mysql_connect("123.123.123.2", "abc_ard", "5555") or die(mysql_error());
mysql_select_db("55_servermail") or die(mysql_error());
chdir(dirname(__FILE__));
$fd = fopen("php://stdin", "r");
$email = "";
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
if(strlen($email)<1) {
die();
}
// handle email
$lines = explode("\n", $email);
// empty vars
$from = "";
$to="";
$subject = "";
$headers = "";
$message = "";
$splittingheaders = true;
for ($i=0; $i < count($lines); $i++) {
if ($splittingheaders) {
// this is a header
$headers .= $lines[$i]."\n";
// look out for special headers
if (preg_match("/^Subject: (.*)/", $lines[$i], $matches)) {
$subject = $matches[1];
}
if (preg_match("/^From: (.*)/", $lines[$i], $matches)) {
$from = $matches[1];
}
if (preg_match("/^To: (.*)/", $lines[$i], $matches)) {
$to = $matches[1];
}
} else {
// not a header, but message
$message .= $lines[$i]."\n";
}
if (trim($lines[$i])=="") {
// empty line, header section has ended
$splittingheaders = false;
}
}
mysql_query("INSERT INTO mail
(`to`,`from`,`header`,`subject`,`msg`,`original`)
VALUES
('{$to}','{$from}', '{$headers}','{$subject}','{$message}','{$email}')") or die(mysql_error());;
?>
When adding information to mysql you have to account for characters used by mysql and PHP and address them as they can cause code to fail, and even allow people to insertand/or execute code on your site. The simplest method I have used is to have PHP "escape" the characters to allow them to insert into mysql properly as follows:
$email = "This isn't my first time 'round here";
This should insert fine as is, but let's presume that your SQL is like this:
$query = "INSERT INTO table (timestamp,email) VALUES (time(),'$email')";
the single quotes in the MySQL query will be jacked up by the single quotes in your data. In order to avoid this set your email variable to be escaped:
$email = "This isn't my first time 'round here";
$email = mysql_escape_string($email);
The caviat to using this is that now your database has extra escape characters (typically a backslash "/") in your data, so when you want to use these from the database you will have to remove them and PHP has a handy function just for this:
$query = "SELECT * FROM table WHERE id='the id you want'";
$result = mysql_query($query) or die(mysql_error());
while ($data = mysql_fetch_array($result)) {
$email = stripslashes($data['email']);
}
echo "This is your email text from the database: <br>\n".$email."<br>\n";
Hope that helps to clarify one possible solution (if that is indeed why the email is not inserting into the database as expected).
the only error that I could possibly see in this current code is the possibility of entering characters like apostrophe(') please verify that if you want it to be included on the message body or other fields make sure to use the backslash() e.g (\') so that mysql will analyze it as a charater and not a closing apostrophe, but do have a security measure on doing that to avoid sql injection. :)