简体   繁体   中英

PHP code in HTML mail

I am working on an application that is used for managing the groups of recipients and multiple contents to send

I want to use different html design so i saved it in a table with some PHP code in it.

But problem is this, I m not getting the PHP code executed when send mail using these HTML contents.

I m using PHPMailer for sending mails and saved HTML contents using addslashes and getting back with stripslashes.

Thanks.

Saved HTML contents using addslashes and getting back with stripslashes.

That's bad. I don't know why you did, but if your intention was to escape queries, use mysql_real_escape_string() , or an analgoue function for your DB driver (or use parametrized queries).
If your intention was to, I don't know, sanitize html? well, that's useless. So no need to add slashes here for any reason.

But problem is this, I m not getting the PHP code executed when send mail using these HTML contents.

Because your content is returned as a string, so PHP will read it as such, tags included.

A dirtiest solution, AND HIGHLY DISCOURAGED , is using eval() to evaluate php code and have it executed. But this is very risky and can lead to serious security problems, so I'm not even going to show you some example :)

The BEST SOLUTION is to use some sort of templating system. I'm not suggesting using Smarty or another full-blown template engine, but you can roll-out a simple custom-code parser that can work along these lines:

You save your variables using a placeholder, like

{{variable_text}}  {{recipient}} {{address}}

or something like this. The you just replace what you need, so in your PHP script that reads this e-mail you can do like

$change = array('recipient' => 'John Smith',
                'address' => 'Unknown Avenue, 666',
                'variable_text' => 'We are glad to invite you to');

$text = '<p>To: {{recipient}}.</p>
         <p>Address: {{address}}.</p>
         Message: Dear{{recipient}}<br />{{variable_text}}';
foreach($change as $k => $v)
{
   $text = str_replace('{{'.$k.'}}', $v, $text);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM