Reputation: 924
Hi there I'm trying to send an HTML email through a PHP webform. The form works fine and if I pass the variables such as $name, $address in to the message it goes through ok, but when I try to format it using HTML I can't seem to get those variables passed into the message. This is an example code I found on w3schools but I can't seem to adjust it to do what I want:
<?php
....
$to = "[email protected], [email protected]";
$subject = "HTML email";
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
</table>
</body>
</html>
";
....
?>
What I'm trying to do is pass the variable $name where it says "john doe", and I guess once I figure that out I should be able to pass through all my other variables as well.
Thanks in advance for all your help.
Upvotes: 1
Views: 23657
Reputation: 22947
You can do it simply like this:
$message = "
<html>
...
<tr>
<td>".htmlspecialchars($name)."</td>
</tr>
...
</html>
";
It's very import to escape content that isn't controlled by you (i.e. collected from a form) to prevent injection attacks. In this case, we use htmlspecialchars
.
Upvotes: 0
Reputation: 4054
In order to get your variables into the message, if you are using double quotes, you should just be able to include the variable in the string:
eg
$message = "
<html>
...
<tr>
<td>$name</td>
</tr>
...
</html>
";
You can also break out of the string
$message = "
<html>
...
<tr>
<td>".$name."</td>
</tr>
...
</html>
";
Which will work with single or double quotes (personally I prefer this method with single quotes).
However when you receive this email, you will see the raw html. In order to have the html displayed properly you will need to set the appropriate mail headers. There are examples of how to do this here and here
Upvotes: 1
Reputation: 35341
You should split the name into two idivdual variables e.g. $first_name
and $second_name
. This is possible to by doing this:
<?php
$split_names = explode(' ', $name); // assuming you have a space between both
$first_name = $split_names[0];
$last_name = $split_names[1];
?>
Then you can do this:
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>" . $first_name . "</td>
<td>" . $second_name . "</td>
</tr>
</table>
</body>
</html>
";
....
?>
Upvotes: 0
Reputation: 27845
$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This email contains HTML Tags!</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>".$firstname."</td>
<td>".$lastname."</td>
</tr>
</table>
</body>
</html>
";
Upvotes: 1