Reputation: 557
I've been stumped for the past couple of hours...
I want to send an email with an HTML header, PHP file body, and HTML footer. This email will be sent from a PHP script. Here's what I have:
/************************ send_email.php *******************/
$first_name = John; //I want to use this variable in body.php
$to = "[email protected]";
$subject = "This is a test email";
//create the header for the email
$header = 'header_email.html';
$fd = fopen($header,"r");
$message_header = fread($fd, filesize($header));
fclose($fd);
//create the body for the email
$body = 'body.php';
$fd = fopen($body,"r");
$message_body = fread($fd, filesize($body));
fclose($fd);
$footer = 'footer_email.php';
$fd = fopen($footer,"r");
$message_footer = fread($fd, filesize($footer));
fclose($fd);
//the final message consists of the header+body+footer
$message = $message_header.$message_body.$message_footer;
mail($to, $subject, $message); //send the email
/************************ end send_email.php *******************/
/************************ header_email.html *******************/
<html>
<body>
/************************ end header_email.html **************/
/************************ body.php *******************/
//some HTML code
<?php echo $first_name; ?>
//some more HTML code
/************************ end body.php **************/
/************************ footer_email.html *******************/
</body>
</html>
/************************ end footer_email.html *************/
The problem with this code is that the email does not send the variable $first_name in the body. The variable is null. It's as if the PHP code is not executing and it's treated as an HTML file.
Could anyone help me solve the problem of using a variable in the body of an external PHP file that I include and send it in an email?
Thanks.
Upvotes: 1
Views: 1657
Reputation: 85468
You are reading the file's contents and then inserting it into the body. This means any PHP code in it won't get executed.
What you want to do is to use include
and output buffering; something like:
ob_start(); // start output buffering
$body_file = 'body.php';
include $body;
$body_output = ob_get_contents(); // put contents in a variable
ob_end_clean();
What output buffering does is "capture" output that would otherwise just be printed to the browser. Then you can put them in a variable like I did ($body_output = ob_get_contents();
) or flush it (actually send it to the browser).
Upvotes: 1