line break issues with sending phpmail - php

please i am trying to make the message show on newline as the customer types it, but i am getting /r/n between each line and also trying to make the $body .= $_SESSION['username']; appear on a separate line i have tried to use this example to solve but has not been successful the code is below
<?php require_once("include/session.php");?>
<?php require_once("include/dataconnect.php");?>
<?php require_once("include/functions.php");?>
<?php include("include/mheader.php");?>
<?php
$submit = $_POST['Notify'];
$message = mysql_real_escape_string(htmlentities(strip_tags($_POST['message'])));
//echo "$message";
//die();
if('POST' === $_SERVER['REQUEST_METHOD'])
{
if (isset($message))
{
//Get Email Address
$emails = mysql_query("SELECT email FROM reusers WHERE username = '{$_SESSION['username']}'")or die(mysql_error());
//$emails = mysql_query("SELECT reusers.email FROM reusers INNER JOIN repplac ON reusers.username = repplac.Uname AND reusers.username = '".$_SESSION['username']."'")or die(mysql_error());
$results = (mysql_fetch_assoc($emails)) or die(mysql_error());
$email= $results['email'];
//echo "$email";
//die();
if(mysql_num_rows($emails) == 0){
exit("No email addresses found for user '{$_SESSION['username']}'");
}
$email = mysql_result($emails, 0);
//echo "$email";
//die();
$body = $_SESSION['username']. "<br>"
. nl2br($_POST['message']);
$to = $email;
$subject = "copy of your notification";
$headers = "From: noti#r.co.uk\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'Bcc:noti#r.co.uk' . "\r\n";
mail($to,$subject,$body,$headers);
}
}
?>
<p>
<form action='notification.php' method='Post' class='rl'>
<div>
<label for='message' class='fixedwidth'>Message</label>
<textarea name="message" rows ="7" cols="40" id="message"></textarea>
</div>
<div class='buttonarea'>
<p>
<input type='submit' name='notify' value='Notify'>
</p>
</div>
</form>
</p>
<?php include("include/footer.php");?>

Since it's generally safer to send HTML emails in a more archaic form of HTML I'm going to allow the HTML email content to be HTML 4; so it doesn't need to be XML well formed and nl2br() is acceptable.
You're specifying that the content of your email is HTML so normal line endings, \r, \n and \r\n are pretty much irrelevant.
Try something like:
$body = $_SESSION['username']. "<br>"
. nl2br($_POST['message']);
There's no sanity checks or validation in there but I think that's what you're trying to get it to do.
---- EXAMPLE CODE ----
I've just refactored your code somewhat so I could better see what you're doing (it's just a matter of personal preference) and put comments in to show what I'm getting at with regards to sanity checks and validation.
I've not tested any of this, it's pretty much just an example using your code.
<?php
require_once "include/session.php";
require_once "include/dataconnect.php";
require_once "include/functions.php";
require_once "include/mheader.php";
//sanity checks - ensure the form has been posted and that there IS a message
if($_POST && !empty($_POST['message'])) {
//sanity check - ensure there IS a username
$sUsername = !empty($_SESSION['username']) ? $_SESSION['username'] : "";
if($sUsername) {
//check the username against the database?
$resultEmail = mysql_query("SELECT `email` FROM `reusers` WHERE `username` = '{$sUsername}' LIMIT 0, 1")
or die(mysql_error());
//no result - could throw an Exception here
if(mysql_num_rows($resultEmail) == 0) {
die("No email addresses found for user '{$sUsername}'");
}
//email verified against the database
else {
$sEmail = mysql_result($resultEmail, 0);
//create the email
$headers = "From: noti#r.co.uk\r\n"
. 'MIME-Version: 1.0' . "\r\n"
. 'Content-type: text/html; charset=iso-8859-1' . "\r\n"
. 'Bcc:noti#r.co.uk' . "\r\n";
$to = $sEmail; //assuming the email address retrieved from the database has already been mxrr checked etc...
$subject = "copy of your notification";
$body = $sUsername . "<br>"
//remove slashes as this is going in an email, strip tags and convert newlines to "<br>"
// since you're using iso-8859-1 there shouldn't be any oddities unless someone completes
// the form using an Arabic character set (for instance)
. nl2br(strip_tags(stripslashes($_POST['message'])));
//send the email
if(!mail($to, $subject, $body, $headers)) {
die("sendmail error!");
}
}
}
}
?>

try this;
$body = "Username" . "<br>";
$body .= "test1 message for test 1 message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1message for test 1
test2 message for test 2
test3 message for test 3";
$body = nl2br($body);
and here what i got

Related

PHP Sending Duplicate Emails

After some more troubleshooting I believe I found the problem. We use QR Tags for our product and when a QR code is scanned it takes the user to the URL that runs this script. If I manually type in the URL or if I use our custom built QR scanner app then the user will receive one email. However if I user any other QR scanning app then it will send multiple emails. How can I make it so that this script will run only once each time the URL is loaded even if its from a third party app?
<?php
$queryString = $_SERVER['QUERY_STRING'];
$count=-6;
$id=substr($queryString,$count,6);
//db connection
$db = new mysqli('localhost', '*****', '*****', '*****');
if (mysqli_connect_errno()) {
echo 'Error: Could not connect to database. Please try again later.';
exit;
}
$query = "SELECT * FROM `****` where id = '$id'";
$result = $db->query($query);
$row = $result->fetch_assoc();
$email = $row['email'];
$ownername = $row['ownername'];
$petname = $row['petname'];
//check to see if tag has been registered
if ($email != "") {
//send email
$datetime = date("D M j G:i:s T Y");
$subject = "Alert";
$mailheader.= "From: " . "Tag Team <support#tag.com>\n";
$mailheader.= "X-Sender: " . "support#tag.com\n";
$mailheader.= "Return-Path: " . "support#tag.com\n";
$mailheader .= "Bcc: support#tag.com";
$body .= "Dear " . $ownername . ", \n\n";
$body .= "" . $petname . "'s Tag has just been scanned.\n\n";
$body .= "Click here to Login :\n";
$body .= "http://www.tag.com\n";
$body .= "********************\n\n";
$body .= "Regards,";
$body .= " \n\n";
$body .= "Tag Team";
$body .= " \n\n";
$body .= "Keeping Pets Safe and Found";
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
//end email alert
}
header("Location: http://www.smartphonepettag.com/id/profile.php?id=$id");
mysql_close($db);
?>
In the code snippet I cannot see any reason why your script should be executed more than once but relating to your post yesterday it seems as if something on your mail server is going terribly wrong.
But anyway if it's not an mail server fault the solution would be something like this:
// add this at the very first line
session_start();
// add this in the code
if($_SESSION['send'] != true){
mail($email, $subject, $body, $mailheader ) or die ("Mail could not be sent.");
$_SESSION['send'] = true;
}
This will make sure that the "mail()" function will never be executed twice for the same user.
You can learn more about Session Variables at the PHP manual.
You could create a flag in your database indicating if the email has been sent. Check the flag before sending the email, set it after you send the email.

Mail function on Live Server is Not sending Mails

I have a website and have enabled to send mail using the By default mail function of php
My code is this
I have tested it from other posts also.. and for me it is correct.. but it is still not sending the message. Please tell me.. where is the problem
<?php
include_once './config.php';
$con=mysqli_connect(mysql_host,mysql_user,mysql_password,mysql_database);
$Roll = $_REQUEST['UserName'];
ini_set('display_errors',1);
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
$confirmCode = md5(uniqid(rand()));
$tbl_name1 = "temp_forgot_acc";
$orderCheck = "DELETE FROM $tbl_name1 WHERE EmailId = '$Roll'";
mysqli_query($con,$orderCheck);
$order = "INSERT INTO $tbl_name1 (EmailId,confirm_code) VALUES ('$Roll','$confirmCode')";
$result = mysqli_query($con,$order);
//if($result)
// {
// ---------------- SEND MAIL FORM ----------------
// send e-mail to ...
$to=$Roll;
// Your subject
$subject="Your Forgot Pass link here";
// From
$header = 'From: Admin <admin#test.com>' . "\r\n";
// Your message
$message="Your Comfirmation link \r\n";
$message.="http://www.test.com/test.html?passkey=$confirmCode&Email=$Roll";
// send email
mail($to,$subject,$message,$header);
// }
echo '{"data":[';
echo "{" . '"Finish":'.'"YES"}';
echo ']}';
}
mysqli_close($con);
exit();
?>
I am able to insert it in the database... but it is not sending the maill.
Try code something like this in your application:
$from = "sender id" // sender must be valid
$subject = "subject";
$message = 'mail from'.$from.'sender';
$to = "receiver id";
// send mail
$headers = 'From: <test#test.com>' . "\n";
$headers .= "MIME-Version: 1.0\n" ;
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\n";
mail($to,$subject,$message,$headers);
and check what you have in $to value..email id must be correct.

php email approval

I have a small web app where people can send a message via email to a group. Because of spam I will have to make an approval procedure.
The messages are being sent via PHP. How am I doing so I have to accept the message before its send to an email that forward it to the group?
My PHP:
<?php
$errors = '';
$myemail = 'whatever#gmail.com';//<-----Put Your email address here.
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['message']))
{
$errors .= "\n FEJL: Alle felter skal udfyldes";
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];
$email_subject = "Form request";
$times = $_POST["timeslots"];
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
$errors .= "\n FEJL: Ugyldig email adresse";
}
$strTimes = implode($times);
if( empty($errors))
{
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
//redirect to the 'thank you' page
header('Location: thx.html');
}
?>
ok so this is a fair size project in itself if you want to use a data queue.
ASSUMING you want to use a database you will need to know the basics of setting one up, how to use and setup tables etc. (as long as you have access to a database anyway).
Here is some connection code:
change peter and abc123 to whatever username and password your database has associated with it.
$con = mysql_connect("localhost","peter","abc123");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db");
I will give you some sample code for inserting rows to the database, selecting rows from the database, acting on that info and deleting rows from the database.
Ok lets start with the mail submission:
This section near the bottom of your code is the data we need to manipulate
$to = $myemail;
$email_subject = "$message \n ";
$email_body = "\n Code: $strTimes \n Navn: $name \n Email: $email_address \n";
$headers = "From: $email_address\n";
$headers .= "Reply-To: $email_address";
So assuming you have a mysql database connection with a table setup in the database this is how you would insert it: (please note this is a basic insert query)
$query = "INSERT INTO queuemails (to, subject, body, headers) VALUES ('" . $to . "', '" . $email_subject . "', '" . $email_body . "', '" . $headers . "')";
mysql_query($query);
Ok so those 2 lines would be added BELOW your set variables.
You then need to provide a method of approval page.
This can be done on the same page but you have to seperate out your mail() function from the rest of the script.
Ok so here is a select script now to be able to VIEW your queue for approval. Please note that I have added an auto increment column to the table that stored your queued mail. This is to be able to select a line in the table more easily as is generates a unique number for that line of data. This column is called mid (standing for "mail identity").
ok so here is the selection script:
$query = "SELECT * FROM queuemail"; //this is only good if you know you wont get millions else you need to limit it
//limited select:
//$query = "SELECT * FROM queuemail LIMIT 0,10"; //selects the first 10
while($m = mysql_fetch_assoc(mysql_query($query))){
echo $m['to'] . " ";
echo $m['subject'] . " ";
echo '<a href=approve.php?mid=' . $m['mid'] . '>Approve</a><br>';
}
Then finally to clean up afterwards, after you have used your mail() function you should delete the line from the database that you have sent.
Here is the code (including the $_GET variable, this is an unsafe method but is sufficient to display the code you would be using).
mail(); //data can be added either from a new select statement or from POSTING it with the form
$query = "DELETE FROM mailqueue WHERE mid='" . $_GET['mid'] . "'";
mysql_query($query);
echo 'Your mail has been sent and deleted from the queue';
Hope this helps.
You can add timestamps to another column in the database automatically so that you can verify spam posting with something like:
if($_SERVER['REQUEST_TIME'] > ($oldtimeofpost + 100)){ //time is in seconds
//do something
}
else{
//warning
}

How to use php function to report form abuse

I have a contact form on my website, and everything works like a charm. I am using a anti-injection validation script, that I suspect is supposed to send a notification when somebody attempts to use header injection. I have tested this thouroghly and cannot determine why it will not notify me on the event of an abuse. The script is below.
<?php
/* Set e-mail recipient */
$myemail = "email#gmail.com";
/* Check all form inputs using check_input function */
$subject = check_input($_POST['subject'], "Please enter your name");
$email = check_input($_POST['email'], "Please enter your email");
$form = check_input($_POST['form'], "Please write your message");
function logbad($value)
{
// Start of validation; this is where the problem is
$report_to = "email#gmail.com";
$name = "Matt";
$mail = "$email";
// replace this with your own get_ip function...
$ip = (empty($_SERVER['REMOTE_ADDR'])) ? 'empty'
: $_SERVER['REMOTE_ADDR'];
$rf = (empty($_SERVER['HTTP_REFERER'])) ? 'empty'
: $_SERVER['HTTP_REFERER'];
$ua = (empty($_SERVER['HTTP_USER_AGENT'])) ? 'empty'
: $_SERVER['HTTP_USER_AGENT'];
$ru = (empty($_SERVER['REQUEST_URI'])) ? 'empty'
: $_SERVER['REQUEST_URI'];
$rm = (empty($_SERVER['REQUEST_METHOD'])) ? 'empty'
: $_SERVER['REQUEST_METHOD'];
$headers = "MIME-Version: 1.0\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\n";
$headers .= "X-Priority: 1\n";
$headers .= "X-MSMail-Priority: Normal\n";
$headers .= "X-Mailer: php\n";
$headers .= "From: \"".$nama."\" <".$mail.">\r\n\r\n";
#mail
(
$report_to
,"[ABUSE] mailinjection # " .
$_SERVER['HTTP_HOST'] . " by " . $ip
,"Stopped possible mail-injection # " .
$_SERVER['HTTP_HOST'] . " by " . $ip .
" (" . date('d/m/Y H:i:s') . ")\r\n\r\n" .
"*** IP/HOST\r\n" . $ip . "\r\n\r\n" .
"*** USER AGENT\r\n" . $ua . "\r\n\r\n" .
"*** REFERER\r\n" . $rf . "\r\n\r\n" .
"*** REQUEST URI\r\n" . $ru . "\r\n\r\n" .
"*** REQUEST METHOD\r\n" . $rm . "\r\n\r\n" .
"*** SUSPECT\r\n--\r\n" . $value . "\r\n--"
,$headers
);
}
// Check 1
//First, make sure the form was posted from a browser.
// For basic web-forms, we don't care about anything
// other than requests from a browser:
if(!isset($_SERVER['HTTP_USER_AGENT']))
{
die('Forbidden - You are not authorized to view this page (0)');
exit;
}
// Cek 2
// Make sure the form was indeed POST'ed:
// (requires your html form to use: action="post")
if(!$_SERVER['REQUEST_METHOD'] == "POST")
{
die('Forbidden - You are not authorized to view this page (1)');
exit;
}
// Host names from where the form is authorized
// to be posted from:
$authHosts = array("cover.com");
// Where have we been posted from?
$fromArray = parse_url(strtolower($_SERVER['HTTP_REFERER']));
// Test to see if the $fromArray used www to get here.
$wwwUsed = strpos($fromArray['host'], "www.");
// Make sure the form was posted from an approved host name.
if(!in_array(($wwwUsed === false ? $fromArray['host'] : substr(stristr($fromArray['host'], '.'), 1)), $authHosts))
{
logbad("Form was not posted from an approved host name");
die(' Forbidden - You are not authorized to view this page (2)');
exit;
}
// Attempt to defend against header injections:
$badStrings = array("content-type:",
"mime-version:",
"content-transfer-encoding:",
"multipart/mixed",
"charset=",
"bcc:",
"cc:");
// Loop through each POST'ed value and test if it contains
// one of the $badStrings:
foreach($_POST as $k => $v)
{
foreach($badStrings as $v2)
{
if(strpos(strtolower($v), $v2) !== false)
{
logbad($v);
die('<strong>Form processing cancelled:<br /></strong> string
(`'.$v.'`)<strong> contains text portions that
are potentially harmful to this server. <br />Your input
has not been sent! <br />Please use your browser\'s
`back`-button to return to the previous page and try
rephrasing your input.</strong>');
exit;
}
}
}
// Made it past spammer test, free up some memory
// and continuing the rest of script:
unset($k, $v, $v2, $badStrings, $authHosts, $fromArray, $wwwUsed);
/* If e-mail is not valid show error message */
$addr_spec = '([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c'.
'\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|\\x22([^\\x0d'.
'\\x22\\x5c\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x22)'.
'(\\x2e([^\\x00-\\x20\\x22\\x28\\x29\\x2c\\x2e'.
'\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d\\x7f-\\xff]+|'.
'\\x22([^\\x0d\\x22\\x5c\\x80-\\xff]|\\x5c\\x00'.
'-\\x7f)*\\x22))*\\x40([^\\x00-\\x20\\x22\\x28'.
'\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40\\x5b-\\x5d'.
'\\x7f-\\xff]+|\\x5b([^\\x0d\\x5b-\\x5d\\x80-\\xff'.
']|\\x5c[\\x00-\\x7f])*\\x5d)(\\x2e([^\\x00-\\x20'.
'\\x22\\x28\\x29\\x2c\\x2e\\x3a-\\x3c\\x3e\\x40'.
'\\x5b-\\x5d\\x7f-\\xff]+|\\x5b([^\\x0d\\x5b-'.
'\\x5d\\x80-\\xff]|\\x5c[\\x00-\\x7f])*\\x5d))*';
if (!preg_match("!^$addr_spec$!", $email))
{
show_error("E-mail address not valid");
}
if (strtolower($_POST['code']) != 'rowingcover') {die('The following error occured: <br />Wrong anti-spam code. <br />
Go back');}
/* Let's prepare the message for the e-mail */
$message = "Cover.com Contact Form
From:
$subject
$email
Message
$form
";
/* Send the message using mail() function */
mail($myemail, $subject, $message, "From: $email");
/* Redirect visitor to the thank you page */
header('Location: contact_received.html');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Please correct the following error:</b><br />
<?php echo $myError; ?><br />
Go back
</body>
</html>
<?php
exit();
}
?>
I am relatively new to php, so any help would be much appreciated.
Thanks,
Matt
Your problem might be that you are using double quotes with # in your variable:
should be: $report_to = 'email#gmail.com'; or $report_to = "email\#gmail.com";
Just posting as answer from my comment since you got it solved by that.
The thing was that using an array inside a variable without scaping it will result in a empty array in your case which would give you a possible wrong email.
You welcome :)
I have found a few things that might contribute to that.
1)
$mail = "$email";
$email isn't defined (you're inside a function), and there is no reason to put quotes around a variable. This means $mail = "";
2)
$headers .= "From: \"".$nama."\" <".$mail.">\r\n\r\n";
You said $nama instead of $name, this means that line is actually:
$headers .= "From: <>\r\n\r\n";
It's a bit difficult to see the reason. Try defining your subject and message before your mail function (makes it much easier to read).
Don't use the "#mail" as that will NOT tell you any errors it runs into. While debugging, you definitely want error messages.
Try sending a normal text email before you send an HTML error (in that function), it might help make things simple. Then slowly implement HTML, see where it breaks.
This following lines looks wrong.
$mail = "$email"; should be $mail = $email;
#mail( should be just mail( This is probably the line preventing your mail being sent!
mail($myemail, $subject, $message, "From: $email"); should be
mail($myemail, $subject, $message, "From:".$email);
Hope that helps.
Thanks to Prix who answered my question in the comments:
$report_to = "email#gmail.com"; either
use single quote or scape the #
$report_to = 'email#gmail.com'; or
$report_to = "email\#gmail.com"; since
the # is treathed as an array it will
not read as email#gmail.com under
double quotes. – Prix 4 mins ago

Any suggestions on how to trouble shoot internal server error for an almost identical script?

On my site I have a contactUser.php that sends mail and a replyMail.php. I have put PHPMail on my contact user to send email notifications which is working great. When I put the same code chunk on my replyMail (which mail goes to the same place as the contact user mail,the inbox) that shares the same variables its giving me a internal server error. I have tried different GET vars as well as echoed die($vars) and echoed queries. Any ideas what the problem might be. Here is my code:
$prof = new User($_GET['id']);
$query = "SELECT `Email` FROM `Users` WHERE `id` = '" . $prof->id . "'";
$request = mysql_query($query,$connection) or die(mysql_error());
$result = mysql_fetch_array($request);
$Email = $result['Email'];
$to = $Email;
$subject = "$auth->first_name $auth->last_name sent you a message";
$message = "$auth->first_name $auth->last_name sent you a message:<br /> <br /> <a href='http://www.blah.org/Inbox.php'>Click here to view</a><br /><br /> The Team";
$from = "blah<noreply#blah.org>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From:$from";
mail($to, $subject, $message, $headers);
I really suggest wrapping it up into a function. From what you've posted, I get the sense that you have all the code in the global namespace, in which case any number of auto-prepends or includes could easily be messing with variables.
Something like:
// Function that accepts a user object and a database connection, then sends a notice email.
function email_message_notice($prof, $connection){
$query = "SELECT `Email` FROM `Users` WHERE `id` = '" . $prof->id . "'";
$request = mysql_query($query,$connection) or die(mysql_error());
$result = mysql_fetch_array($request);
$Email = $result['Email'];
$to = $Email;
$subject = "$auth->first_name $auth->last_name sent you a message";
$message = "$auth->first_name $auth->last_name sent you a message:<br /> <br /> <a href='http://www.blah.org/Inbox.php'>Click here to view</a><br /><br /> The Team";
$from = "blah<noreply#blah.org>";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From:$from";
$res = mail($to, $subject, $message, $headers);
return $res;
}
$prof = new User($_GET['id']);
$sent = email_message_notice($prof, $connection);
Since there's a database involved, this is untested code, so you'll want to test that it works and want to debug any further issues yourself, but otherwise it should be a good way to compartmentalize and share the code. If you're doing exactly the same thing in both scripts, you can just include the email_user function in a separate include.
Look into the server log. Should tell you what is wrong. Maybe file permissions.
Is that the whole script? I can't see anything there that could cause a 500 error. Can you post the whole page or a link to the source code of the whole page?
Is this a part of some loop or mass mailing that gets called repeatedly?
Is there no way to get hold of the Apache error logs? Only they will give you a definite answer what goes wrong.

Categories