user3450364
user3450364

Reputation: 39

HTML in PHP mail

I have a little problem, but I can't find out how to solve it.. (Code first)

Here is my PHP code:

<?php
 // Simple basic check
 function checkData($mandatory_fields, $field_input) {

$check = true;
foreach($mandatory_fields as $key=>$value) {

    if(empty($field_input[$value])) {
        $check = false;
    }
}
return $check;
}

function unserializeData() {
$serializedData = $_POST['value'];
$unserializedData = array();
parse_str($serializedData, $data);
return $data;
}

function mailContactForm() {
$data = unserializeData();
$mandatory = array("comment_name", "comment_email", "comment_message", "titel",   "email_adverteerder","advertentie_titel","prijs");
if (!checkData($mandatory, $data)) {
    header("HTTP/1.1 400 Bad Request");
    return false;
}

$to = $data["email_adverteerder"];
$from = $data["comment_name"];
$subject = 'You have a new message ' .$data["titel"] ;
$message = '
<html>
<head>

</head>
 <body>
  '. $data["comment_message"].'<br><br> 
</body>
</html>
';
$headers  = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From:".$data["comment_name"]."<".$data["comment_email"].">" . "\r\n" .
"Reply-To: ".$from."" . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);

}

mailContactForm();

?>

Html code:

<div>
 <label for="comment-text">Uw reactie:  <span class="mandatory">*</span></label>
  <textarea id="comment-text" name="comment_message"></textarea>
</div>

Like I sayed my code is working fine (Im getting the mail) except the $data["comment_message"]. The problem is when I get the message is not the same when i had send it.

Example: If I write in my html textarea this: Hello World,

Im very happy

Im getting this in my email: Hello World,Im very happy.

So he dosen't making a newline..

I hope I gave you enough information to help me.

Upvotes: 0

Views: 61

Answers (1)

Devon Bessemer
Devon Bessemer

Reputation: 35337

A textarea value won't just output HTML code and you probably don't want a user to be able to submit HTML code through a textarea.

Use nl2br() to convert a new line character to an HTML line break.

I would run nl2br(htmlentities($data["comment_message"]));

htmlentities() will convert HTML code to special entities so it won't execute the code but will just display it. For instance: <img src='...' /> in the textarea won't display an image, it will just display the code.

Upvotes: 2

Related Questions