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");
Related
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.
This question already has answers here:
Dollar ($) sign in password string treated as variable
(8 answers)
Closed 8 years ago.
I use a mailscript with a dynamic body-field, so an admin user can build it's own BODY. But in the body I need the have some variables.
Example of an input of an admin user:
Dear [name] from [company],
thanks for registering
This text will be INSERTed in a table. But now I want to use this input for building an automatic mail. So the content of $body should be:
Dear $name from $company,
thanks for registering
This is my code:
$inserted_text = addslashes($_POST['inserted_text']);
$patterns = array();
$patterns[0] = '/[name]/';
$patterns[1] = '/[company]/';
$replacements = array();
$replacements[1] = '$name';
$replacements[0] = '$company';
$inserted_text_dynamic = (preg_replace($patterns, $replacements, $inserted_text));
$body = <html><head>...</head><body> $inserted_text_dynamic </body>
mail($to, $subject, $body, $headers);
But the output goes wrong? How can I manage to have content like $name in my $body ?
$replacements[1] = '$name';
$replacements[0] = '$company';
This won't work in the way you intend, because single-quotes suppress the expansion of variables.
Use double-quotes:
$replacements[1] = "$name";
$replacements[0] = "$company";
Or no quotes:
$replacements[1] = $name;
$replacements[0] = $company;
#MichaelBerkowski also correctly points out that you are using square brackets in your regular expression pattern, but square brackets are metacharacters in regular expressions, so you should escape them. Or else choose a different character to delimit your placeholders in your email template. Or use a function that does fixed string replacement instead of regular expressions.
This won't work:
$replacements[1] = '$name';
$replacements[0] = '$company';
Use double-quotes:
$replacements[1] = "$name";
$replacements[0] = "$company";
or no quotes:
$replacements[1] = $name;
$replacements[0] = $company;
Use this:
$body = "<html><head>...</head><body> " . $inserted_text_dynamic . " </body>";
Instead of:
$body = <html><head>...</head><body> $inserted_text_dynamic </body>
And remove firts brackets in
$inserted_text_dynamic = (preg_replace($patterns, $replacements, $inserted_text));
like this:
$inserted_text_dynamic = preg_replace($patterns, $replacements, $inserted_text);
There are many ways to do it you can use it as
echo "Dear $name from $company, thanks for registering";
in double quotation marks variables are auto given there value or if you want to use single quotation marks then you ca try this.
echo 'Dear '.$name. ' from '.$company. ', thanks for registering';
There are several things at play here - syntax errors and improper regex. Here is a complete solution example.
$_POST['inserted_text'] = 'Dear [name] from [company], thanks for registering';
$name = 'foo';
$company = 'bar';
$inserted_text = addslashes($_POST['inserted_text']);
$patterns = array();
$patterns[0] = '/\[name\]/'; // you have to escape square brackets in regex because they are special to regex
$patterns[1] = '/\[company\]/';
$replacements = array();
$replacements[1] = $name; // removed quotes
$replacements[0] = $company; // removed quotes
$inserted_text_dynamic = (preg_replace($patterns, $replacements, $inserted_text));
$body = '<body>' . $inserted_text_dynamic . '</body>';
echo $body;
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.