【问题标题】:PHP - mail() - single quotes vs double quotesPHP - mail() - 单引号与双引号
【发布时间】:2013-02-07 03:59:28
【问题描述】:

我的 PHP mail(); 函数有一个奇怪的问题。

像这样使用它

$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 );

一切都按预期进行。邮件已发送,所有内容均已正确编码,主题也正常。

但是当我用这样的单引号更改双引号时:

$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 );

邮件仍然可以发送,但没有设置主题。相反,它是

www-data@domain.com

特殊字符也会被销毁。那里发生了什么?

【问题讨论】:

    标签: php email


    【解决方案1】:

    需要使用双引号来插入特殊的换行符 ("\r\n")。当您使用单引号时,它们不会被视为换行符,而是会被视为文字。

    PHP 解释器将评估双引号中的材料,但不会对单引号执行此操作。因此,最佳做法是仅在需要评估某些内容时使用双引号(如变量、无法连接时或换行等特殊字符)。

    【讨论】:

      【解决方案2】:

      单引号用于文字字符串,没有变量被替换/扩展,并且除了\'\\ 之外没有任何转义序列被尊重。您编写代码的方式可以保留单引号,除非您必须将换行符双引号为"\r\n"

      【讨论】:

      • @leftclickben ugh,真是太棒了。如果他们只是排除所有逃逸并完成它,那可能会更好。答案已更新。
      【解决方案3】:

      请阅读说明书:

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

      单引号

      要指定文字单引号,请使用反斜杠 () 对其进行转义。到 指定文字反斜杠,将其加倍 (\)。所有其他实例 反斜杠将被视为文字反斜杠:这意味着 您可能习惯的其他转义序列,例如 \r 或 \n,将是 按指定的字面输出,而不是具有任何特殊含义。

      【讨论】:

        猜你喜欢
        • 2016-03-18
        • 2011-09-17
        • 2012-12-13
        • 2011-06-02
        • 2012-12-30
        • 1970-01-01
        • 1970-01-01
        • 2013-02-05
        • 1970-01-01
        相关资源
        最近更新 更多