问题
This is my first time doing this but I really had to, so I've been working with php and have this script that is giving me trouble when it goes to mail. All it is is an ajax POST request sending a code and email to the php script. The problem I am facing is getting the $message string for the first email to be concatenated with the variables. If I just set $message to a string literal and send the email, everything works. But when trying to concatenate some variables into it as shown here no email is sent. Also, when writing the new email and code to the winners.txt file, everything functions properly. Am I concatenating the string wrong? I have tried a few different ways. Thanks!
<?php
$myFile = "winners.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$email = $_POST['email'];
$code = $_POST['code'];
$code = (string)$code . '';
$message = "Winner information follows:\r\nEmail: ";
$message .= strval($email);
$message .= "\r\nConfirmation Code: ";
$message .= strval($code);
fwrite($fh, $email);
fwrite($fh, $code);
mail("loganhsnow@gmail.com", "Winning Notice ST", $message);
mail($email, "Winning Notice CT", ', Congrats, you won a free amazon gift card at logansnow.tk. If the following confirmation code matches the one in our records you will receive your reward. The code follows: ');
fclose($fh);
?>
回答1:
Dont need to do any conversion first of all. So you can get rid of $code = (string)$code . '';
and all the strval() calls. You $message can be set as thus:
$message = "Winner information follows:\r\nEmail: ".$email."\r\nConfirmation Code: ".$code;
Also, it doesnt look like you are including the code in your second email. So the whole thing changed would look like this:
<?php
$myFile = "winners.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$email = $_POST['email'];
$code = $_POST['code'];
$message = "Winner information follows:\r\nEmail: ".$email."\r\nConfirmation Code: ".$code;
fwrite($fh, $email);
fwrite($fh, $code);
mail("loganhsnow@gmail.com", "Winning Notice ST", $message);
mail($email, "Winning Notice CT", 'Congrats, you won a free amazon gift card at logansnow.tk. If the following confirmation code matches the one in our records you will receive your reward. The code follows: '.$code);
fclose($fh);
?>
One other thing to note is that you might want to put $email through some sanitizaiton checks to verify it is a valid email address.
来源:https://stackoverflow.com/questions/23966987/php-string-concatenation-with-variables