This question already has answers here:
Elegant solution for line-breaks (PHP)
(8 answers)
Closed 7 years ago.
I am trying to put breaks on my mail script. Because now I receive all the information in just one line. I have searched for \r\n and stuff but that doesnt work :(
Anyone suggestions? Would be of real help. THnx!
<?php
if($_POST){
$vorm = $_POST['vorm'];
$rente = $_POST['rente'];
$einde = $_POST['einde'];
$waarde = $_POST['waarde'];
$leen = $_POST['leen'];
$aanhef = $_POST['aanhef'];
$voornaam = $_POST['voornaam'];
$achternaam = $_POST['achternaam'];
$postcode = $_POST['postcode'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$message = $_POST['form_msg'];
mail("m.bosch#unit-ict.nl", "Hypotheek aanvraag", $vorm .$rente .$einde .$waarde .$leen .$aanhef .$voornaam .$achternaam .$postcode .$telefoon .$email .$message);
}
You could try the following:
<?php
$vorm = strip_tags( $_POST['vorm'] );
$rente = strip_tags( $_POST['rente'] );
$einde = strip_tags( $_POST['einde'] );
$waarde = strip_tags( $_POST['waarde'] );
$leen = strip_tags( $_POST['leen'] );
$aanhef = strip_tags( $_POST['aanhef'] );
$voornaam = strip_tags( $_POST['voornaam'] );
$achternaam = strip_tags( $_POST['achternaam'] );
$postcode = strip_tags( $_POST['postcode'] );
$telefoon = strip_tags( $_POST['telefoon'] );
$email = strip_tags( $_POST['email'] );
$message = strip_tags( $_POST['form_msg'] );
$naar = "m.bosch#unit-ict.nl";
$onderwerp = "Hypotheek aanvraag";
$bericht =
"
Vorm: {$vorm}\r\n
Rente: {$rente}\r\n
Einde: {$einde}\r\n
Waarde: {$waarde}\r\n
Leen: {$leen}\r\n
Aanhef: {$aanhef}\r\n
Voornaam: {$voornaam}\r\n
Achternaam: {$achternaam}\r\n
Postcode: {$postcode}\r\n
Telefoon: {$telefoon}\r\n
Email: {$email}\r\n
Bericht: {$message}
";
$headers = "From: yourname example#example.com";
mail($naar, $onderwerp, $bericht, $headers);
email()
strip_tags() Prevent HTML tags from being send
Certainly such line breaks will work in email messages. Most likely you applied them wrong somehow. Here is a working example:
<?php
// [...]
mail(
"m.bosch#unit-ict.nl",
"Hypotheek aanvraag",
sprintf("vorm: %s\r\nrente: %s\r\neinde: %s\r\nwaarde: %s\r\nleen: %s\r\naanhef: %s\r\nvoornaam: %s\r\nachternaam: %s\r\npostcode: %s\r\ntelefoon: %s\r\nemail: %s\r\n\r\nmessage:\r\n%s",
$vorm .$rente .$einde .$waarde .$leen .$aanhef .$voornaam .$achternaam .$postcode .$telefoon .$email .$message);
);
Also using heredoc notation would be a very elegant approach:
<?php
// [...]
$content = <<< EOT
vorm: {$vorm}
rente: {$rente}
einde: {$einde}
waarde: {$waarde}
leen: {$leen}
aanhef: {$aanhef}
voornaam: {$voornaam}
achternaam: {$achternaam}
postcode: {$postcode}
telefoon: {$telefoon}
email: {$email}
message:
{$message}
EOT;
mail("m.bosch#unit-ict.nl", "Hypotheek aanvraag", $content);
Note that this will create an empty line between each line on most situation, but you are on the safe side like that. The issue here is that MS-Windows based systems (as often) do things different that defined in all standards.
Related
This question already has answers here:
PHP Linefeeds (\n) Not Working
(11 answers)
Closed 6 years ago.
The code is in double quotes and still not working.
I already read this post
I'm using Atom and am on localhost (if that makes any difference)
I redownloaded Atom (in case there was something going on with the settings) and that didn't help
Here's the code:
<?php
$firstName = 'David';
$lastName = "Powers";
$title = '"The Hitchhiker\'s Guide to the Galaxy"';
$author = 'Douglas Adams';
$answer = 42;
$newLines = "\r\n\r\n";
$fullName = "$firstName $lastName |";
$book = "$title by $author";
$message = "Name: $fullName $newLines";
$message .= "Book: $book \r\n\r\n";
$message .= "Answer: $answer";
echo $message;
echo "Line 1\nLine 2";
Output is all one line, but when I view source the new lines are working
Name: David Powers | Book: "The Hitchhiker's Guide to the Galaxy" by Douglas Adams Answer: 42Line 1 Line 2
This is the first thing you will learn if you are learning even from a PHP 5 For Dummies book. HTML doesn't respect new line or tab or multiple space characters. You have to use <br /> for new lines.
* Sourced from PHP 5 For Dummies by Janet Valade.
Change your code to:
<?php
$firstName = 'David';
$lastName = "Powers";
$title = '"The Hitchhiker\'s Guide to the Galaxy"';
$author = 'Douglas Adams';
$answer = 42;
$newLines = "<br /><br />";
$fullName = "$firstName $lastName |";
$book = "$title by $author";
$message = "Name: $fullName $newLines";
$message .= "Book: $book <br /><br />";
$message .= "Answer: $answer";
echo $message;
echo "Line 1<br />Line 2";
If you are just opting for a text based layout, you can set the header to the browser to respect it as just a text file. For that, you need:
header("Content-type: text/plain");
This will render without any HTML.
By default, when a PHP script is run, the content type of the result is set to text/html. When browsers render HTML, newlines are not normally respected, they're treated like any other whitespace.
If you want all your output formatting to stay the same, and you're not sending HTML, tell the browser that you're sending plain text. Put this at the beginning of the code:
header("Content-type: text/plain");
As well Praveen Kumar mention how to print new lines in echo.
But if you still want to use escape sequences then use print_f You can use other escape sequences like \t,\n in printf.
<?php
$firstName = 'David';
$lastName = "Powers";
$title = '"The Hitchhiker\'s Guide to the Galaxy"';
$author = 'Douglas Adams';
$answer = 42;
$newLines = "\r\n\r\n";
$fullName = "$firstName $lastName |";
$book = "$title by $author";
$message = "Name: $fullName $newLines";
$message .= "Book: $book \r\n\r\n";
$message .= "Answer: $answer";
printf ($message);
printf ("Line 1\nLine 2");
I've been trying to figure out how to finish this PHP script, and I think it would really help me and others looking to try and create a script that saves QR codes and then allows them to be sent to the person who created them. What I'm currently trying to do is create a QR Code Generator that emails a person a QR code generated dynamically from the name and email information information. Basically, the goal here is to do a PHP Get Request in the URL to display a user's dynamic PHP page on the site.
Please let me know if this doesn't make sense, I'd really appreciate any and all help and feel like this is a problem that others might need help with in the future as well!
<?php
if ( isset( $_POST['submit'] ) ) {
$hostname = 'localhost';
$user = 'username';
$pass = 'password';
$dbase = 'database';
$connection = mysql_connect( "$hostname" , "$user" , "$pass" )
or die ( "Can't connect to MySQL" );
$db = mysql_select_db( $dbase , $connection ) or die ( "Can't select database." );
function clean( $var )
{
$dirtystuff = array( "\\", "/", "*", "'", "=", "#", ";", "<", ">", "+", "%" );
return mysql_real_escape_string( str_replace( $dirtystuff , "" , $var ) ) ;
}
$_POST = array_map( "clean", $_POST );
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO qrdb (Name, Email)
VALUES ('$name', '$email');";
mysql_query( $sql ) or die( "Couldn't run the query: " . $sql . " - " . mysql_error()
);
mysql_close();
}
$filename = "$HELPWITHVAR";
$width = 400;
$height = 400;
if (!file_exists($filename))
{
$url = urlencode("DynamicURLHEREWithNameAndEmailInfoInAGetRequestFormat");
$qr = file_get_contents("http://chart.googleapis.com/chart?chs=
{$width}x{$height}&cht=qr&chl=$url");
file_put_contents($filename, $qr);
}
echo "<img src=\"$filename\" width=\"$width\" height=\"$height\" alt=\"Scan my QR !\"
/>";
$to = "$_POST['email']";
$subject = "QR Code for you!";
$message = "
<html>
<body>
<p>Here is your QR Code!</p>
<p><?php echo $filename ?></p>
</body>
</html>";
$headers .= 'From: <email#domain.com>' . "\r\n";
mail($to,$subject,$message,$headers);
?>
You cannot put PHP tags in the email - they won't get executed!
You need to call the image directly
<p>Here is your QR Code!</p>
<p><img src="http://chart.googleapis.com/chart?chs=
400x400&cht=qr&chl=http://example.com/"
width="400" height="400" alt="Scan my QR !" />"
</p>
Replace example.com with whatever the URL is.
I am running the following script, which is phpmailer, at the end of each for each run I want it to clear the contents of $name , either that or $row->['leadname'] , I have tried using unset at the bottom of the script but this seems to have no effect and I am just getting from a list of 3 people 2 of them saying dear bob , and the other saying dear {name} , even though the contacts are called, bob, fred and wendy.
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
?>
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// $body = file_get_contents('contents.html');
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">{message}</div>
</div>
</body>
</html>
';
// $body = preg_replace('/\\\\/i', $body);
$mail->SetFrom('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->AddReplyTo('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->Subject = "Your Fuel Prices From Chandlers Oil & Gas";
$query = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
$result = mysql_query($query);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR);
die();
}
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
// THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
$firstname = $row["leadname"];
//THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
$businessname = $row["businessname"];
// IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
if ($firstname = '')
{$name = $row["businessname"];}
else
{$name = $row["leadname"];}
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$body = str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$body = str_replace('{fuel}', $templatename, $body);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$body = str_replace('{message}', $templateMessage, $body);
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["leadname"]);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
unset ($row['leadname']);
unset ($name;)
}
?>
It looks like you need to copy the contents of body into a new variable within your loop.
Currently you're overwriting the variable on the first run, removing the {name} placeholders.
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$newBody= str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$newBody = str_replace('{fuel}', $templatename, $newBody);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$newBody = str_replace('{message}', $templateMessage, $newBody);
$mail->MsgHTML($newBody);
$mail->AddAddress($row["email"], $row["leadname"]);
Also you can actually use arrays in str_replace, e.g.
$newBody = str_replace(array('{name}','{fuel}'),array($name,$fuel),$body);
the ; is in a wrong position.
Try
unset($name);
instead of
unset($name;),
Anything wrong with this code? I want it to print the name and address - each on a separate line, but it all comes up in one line.
Here's the code
<?php
$myname = $_POST['myname'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$address3 = $_POST['address3'];
$town = $_POST['town'];
$county = $_POST['county'];
$content = '';
$content .="My name = " .$myname ."\r\n";
$content .="Address1 = " .$address1 ."\n";
$content .="Address2 = " .$address2 ."\n";
$content .="Address3 = " .$address3 ."\n";
$content .="town = " .$town ."\n";
$content .="county = " .$county ."\n";
echo $content;
?>
It looks like the '\n' character is not working.
In your source code this will show on a next line, but if you want to go to another line in HTML you will have to append <br />.
So:
$content .="My name = " .$myname ."<br />\r\n";
I left the \r\n here because it will go to the next line in your source code aswell, which might look nicer if you have to view the source.
The \n character properly works just fine. The problem is, it's not what you expect.
If you see this in a browser, you won't see line breaks, because line breaks are ignored in the source code. The HTML parser only reads <br> as line breaks.
If you try to go to your website and view the source code, you'll find that the line breaks are in there.
I am having a strange problem with str_replace in my php code below. What is supposed to happen is on each loop it is supposed to replace {name} with the person's name pulled in from the database. What it is actually doing is if I mail two people, the first one it replaces with thier name, so they get an email dear, bob bla bla bla. The second one always seems to be dear , {name} bla bla bla. It is as though on the second loop, something is failing?
<?php
$formid = mysql_real_escape_string($_GET[token]);
$templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
$templateData = mysql_fetch_object($templatequery);
$gasoiluserTemplate = $templateData->gasoilusers;
$dervuserTemplate = $templateData->dervusers;
$kerouserTemplate = $templateData->kerousers;
$templateMessage = $templateData->mailinglistgroupmessage;
$templatename = $templateData->mailinglistgroupname;
?>
<?php
require_once('./send/class.phpmailer.php');
//include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded
$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch
// $body = file_get_contents('contents.html');
$body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
</head>
<body>
<div style="background:
none repeat scroll 0% 0% rgb(6, 38,
97); width:780px;">
<img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
src="http://www.chandlersoil.com/images/newsletter/header.gif"
alt="Chandlers Oil and Gas"
border="0" height="112"
width="580">
<div id="title">{message}</div>
</div>
</body>
</html>
';
// $body = preg_replace('/\\\\/i', $body);
$mail->SetFrom('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->AddReplyTo('crea#cruiseit.co.uk', 'Chandlers Oil & Gas');
$mail->Subject = "Your Fuel Prices From Chandlers Oil & Gas";
$query = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
$result = mysql_query($query);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR);
die();
}
while ($row = mysql_fetch_array ($result)) {
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!";
// THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
$firstname = $row["leadname"];
//THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
$businessname = $row["businessname"];
// IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
if ($firstname = '')
{$name = $row["businessname"];}
else
{$name = $row["leadname"];}
// THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
$body = str_replace('{name}', $name, $body);
// THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
$body = str_replace('{fuel}', $templatename, $body);
// THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
$body = str_replace('{message}', $templateMessage, $body);
$mail->MsgHTML($body);
$mail->AddAddress($row["email"], $row["leadname"]);
if(!$mail->Send()) {
echo "Mailer Error (" . str_replace("#", "#", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
} else {
echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("#", "#", $row["email"]) . ')<br>';
}
// Clear all addresses and attachments for next loop
$mail->ClearAddresses();
$mail->ClearAttachments();
}
?>
$body contains the mail's template. In your loop, you assign the return value from str_replace() to this variable. After that, you cannot expect it to contain the original template upon a next iteration. You'll have to use a temporary variable for this:
while (...) {
$bodyTemp = str_replace('{name}', $name, $body);
$bodyTemp = str_replace('{fuel}', $templatename, $bodyTemp);
// ...
}
Also, to make your code a little more readable, might I suggest using strtr() instead:
while (...) {
$bodyTemp = strtr($body, array(
'{name}' => $name,
'{fuel}' => $templatename,
// ...
));
}
This saves you the repetitive invocations of str_replace().
Before the loop, $body may contain Dear {name}. Then you loop once, then it contains Dear Iain. Then in the second loop, there is no {name} to replace anymore.