简体   繁体   中英

PHP - mail() - single quotes vs double quotes

I have a strange problem with the PHP mail(); function.

Using it like this

$header  = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type: text/html; charset=utf-8" . "\r\n";
$header .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
$header .= "Reply-To:" . $email . "\r\n";
$header .= "From: Kontaktformular <noreply@thomas-glaser-foto.de>" . "\r\n";
mail( "mail.me@mail.com", "Message from " . $name . " through your website!", $message, $header );

everything works as expected. The mail gets send, everything is encoded correctly and the subject is also ok.

But when I change the double quotes with single quotes like this:

$header  = 'MIME-Version: 1.0' . '\r\n';
$header .= 'Content-type: text/html; charset=utf-8' . '\r\n';
$header .= 'Content-Transfer-Encoding: quoted-printable' . '\r\n';
$header .= 'Reply-To:' . $email . '\r\n';
$header .= 'From: Kontaktformular <noreply@thomas-glaser-foto.de>' . '\r\n';
mail( 'mail.me@mail.com', 'Message from ' . $name . ' through your website!', $message, $header );

The mail still gets send, but without the set subject. Instead, it is

www-data@domain.com

and the special characters are also destroyed. What is happening there?

Double quotes are needed to put in the special linebreak characters ( "\\r\\n" ). They are not treated as linebreaks when you use single quotes, instead they will be treated as literal text.

The PHP interpreter will evaluate material in double quotes, but it doesn't do so to single quotes. Because of this, the best practice is to only use double quotes when something needs to be evaluated (like a variable, when concatenation isn't possible, or special characters like line breaks).

Single quotes are for literal strings, no variables are replaced/expanded, and no escape sequences other than \\' and \\\\ are respected. The way you've written your code you can leave the single-quotes as-is except you must have the line breaks double quoted as "\\r\\n" .

Please read the manual:

http://php.net/manual/en/language.types.string.php

Single quoted

To specify a literal single quote, escape it with a backslash (). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \\r or \\n, will be output literally as specified rather than having any special meaning.

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