【问题标题】:Special characters (utf-8) in PHP contact messagePHP 联系信息中的特殊字符 (utf-8)
【发布时间】:2015-10-03 06:56:22
【问题描述】:

我有一个联系表。当我收到一条消息时,我无法正常阅读,因为特殊字符显示得很奇怪。

我在没有 BOM 的情况下将我的文件保存在 utf-8 中,我红色并尝试了很多关于这个主题的变体,但我找不到适合自己的正确答案。

我的 html 中的联系表格:

<meta charset="utf-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 


<form id="contactform" action="processform.php" method="post" accept-charset='UTF-8'>
    <div class="form-label label-name">Nom</div>
    <input type="text" name="name" id="name" />
    <div class="form-label label-postcode">Code Postal</div>
    <input type="text" name="postcode" id="postcode" />
    <div class="form-label label-email">E-mail</div>
    <input type="text" name="email" id="email" />
    <div class="form-label label-subject">Sujet</div>
    <input type="text" name="subject" id="subject" />
    <div class="form-label label-message">Message</div>
    <textarea rows="4" name="message" id="message"></textarea>
    <input type="submit" id="send" name="button" value="Envoyer" />           
</form>

我的 processform.php 文件(以 UTF-8 保存,没有 BOM)具有以下代码:

<?php

include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';

$securimage = new Securimage();

if ($securimage->check($_POST['verif']) == false) {
  // the code was incorrect
  // you should handle the error so that the form processor doesn't continue

  // or you can use the following code if there is no validation or you do not know how
  echo "Le code de s&eacute;curit&eacute; indiqu&eacute; est incorrect.<br />";
  echo "Rafra&icirc;chissez la page et essayez &agrave; nouveau svp.";
  exit;
}

// Clean up the input values
foreach($_POST as $key => $value) {
  if(ini_get('magic_quotes_gpc'))
    $_POST[$key] = stripslashes($_POST[$key]);

  $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key]));
}

// Assign the input values to variables for easy reference
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$message = $_POST["message"];

// Test input values for errors
$errors = array();
if(strlen($name) < 3) {
  if(!$name) {
    $errors[] = "Entrez votre nom svp.";
  } else {
    $errors[] = "Au moins 3 caractères sont requis pour un nom.";
  }
}
if(!$email) {
  $errors[] = "Entrez votre email svp.";
} else if(!validEmail($email)) {
  $errors[] = "Veuillez fournir une adresse valide svp.";
}
if(strlen($message) < 20) {
  if(!$message) {
    $errors[] = "Entrez un message svp.";
  } else {
    $errors[] = "Au moins 20 caractères sont requis pour un message.";
  }
}

if($errors) {
  // Output errors and die with a failure message
  $errortext = "";
  foreach($errors as $error) {
    $errortext .= "<li>".$error."</li>";
  }
  die("<span class='failure'>Les erreurs suivantes sont survenues :<ul>". $errortext ."</ul></span>");
}

// Remplacement de certains caractères spéciaux
header('Content-Type: text/html; charset=utf-8');

// Send the email
$to = "myemail@gmail.com";
$message = "
From: $name 
Email: $email 
Subject: $subject
Message: $message";
$headers = "Message from West Hungary website";

mail($to, $subject, $message, $headers);

// Die with a success message
die("<span class='success'>Votre message a &eacute;t&eacute; envoy&eacute; avec succ&egrave;s !</span>");

// A function that checks to see if
// an email is valid
function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

?>

【问题讨论】:

  • 附注:由于您使用的是 UTF-8,请考虑使用 php 多字节函数 link。例如:将strlen('è')替换为mb_strlen('è')strlen将返回2而mb_strlen将返回1。其他mb函数为:strrposmb_strrpossubstrmb_substr
  • 谢谢!我在所有strlenstrrpossubstr 中添加了_mb,但我仍然得到奇怪的字符......我去了你给我的链接,这对我来说完全无法理解,但是我发现了一些有趣的东西也许:我如何将它添加到我的关于消息正文的 processform 文件中:mixed mb_strlen ( string $str [, string $encoding = mb_internal_encoding() ] )... 我必须编码的唯一部分,它是我通过邮件收到的消息的正文...
  • 您需要为每个mb_函数传递编码,例如:mb_strlen('è', 'UTF-8');或在文件开头调用mb_internal_encoding('UTF-8'),因此您不需要传递'UTF -8' 用于 mb_ 函数。要使邮件正常工作,请在 $header 中传递 "Content-Type: text/html; charset=UTF-8"
  • IgorLaszlo 你试过用 SwiftMailer 库替换 PHP 函数 mail() 吗?我已经在多种语言的项目中使用过,没有任何问题。它有一个非常完整的文档,您可以在此处查看:swiftmailer.org/docs/overview.html我希望对您有所帮助。
  • @evilReiko - 请写下答案,您将获得赏金!是您的评论驱使我找到解决方案!它只能与mb-strlen$headers "Content-Type: text/html; charset=UTF-8" 一起使用!工作的最终代码如下:mb_strlen('è', 'UTF-8'); mb_strlen('é', 'UTF-8'); mb_strlen('ë', 'UTF-8'); etc. // Send the email $headers = "Content-Type: text/html; charset=UTF-8\n"; $to = "myemail@gmail.com"; $message = " Message from West Hungary website &lt;br /&gt; From: $name &lt;br /&gt; Email: $email &lt;br /&gt; Subject: $subject &lt;br /&gt; Message: $message";

标签: php utf-8 contact-form


【解决方案1】:

尝试将此行添加到标题中,

$headers = 'MIME-Version: 1.0\r\n';
$headers .= "Content-Type: text/html; charset=UTF-8\n";

【讨论】:

  • 您也可以使用utf8_encode()$message = utf8_encode( "De: $name E-mail: $email Code Postal: $value Subject: $subject Message: $message");
  • @Vic 你为什么要 utf8_encode 一个已经 UTF-8 编码的字符串?!
  • 这里我们正在对电子邮件中发送的数据进行编码
  • @Chandu:我如何添加自己的$headers = 'Message via le formulaire de contact du site web Volumes Et Surfaces\r\n'; 行?我的线是第一条还是最后一条?我必须在那里放一个 dat:$headers .= 给我的吗?
  • @IgorLaszlo 您可以使用点分隔符 (.) 连接示例:$headers .= "Message via le formulaire de contact du site web Volumes Et Surfaces\r\n'; 在现有的标头变量之后.
【解决方案2】:

由于您使用的是 UTF-8,请考虑使用 php 多字节函数链接 mb_*。例如:

echo strlen('è'); // output 2
echo mb_strlen('è', 'UTF-8'); // output 1

您可能感兴趣的其他 mb_* 函数:

strrpos()mb_strrpos()

substr()mb_substr()

有关多字节函数的完整列表,请查看here

如果您不想在每个 mb_ 函数中传递“UTF-8”,请在脚本开头调用 mb_internal_encoding('UTF-8')

要使mail() 函数与 UTF-8 一起正常工作,请在标头中传递以下内容:

$header = "Content-Type: text/html; charset=UTF-8"

【讨论】:

  • 非常感谢!现在消息正文显示正常字符...我得到了很多很好的答案,但他们并没有单独工作...你的已经完成了。
  • 在你进入臭名昭著的“UTF-8 地狱”之前,没有人知道 UTF-8 是如何工作的!
【解决方案3】:

1-确保在你的 HTML 头部有这个:

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

2-然后将其添加到 PHP 脚本的开头:

header('Content-Type: text/html; charset=utf-8');

前两步示例:

<!DOCTYPE html>
  <html>
    <head>
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"
      <title>PHP Special Characters</title>
    </head>
    <body>
      <?php
         $header= "MIME-Version: 1.0\r\n"; 
         $header.= "Content-type: text/html; charset=iso-8859-1\r\n"; 
         echo "àè";
      ?>
    </body>
  </html>

除了第 2 步,您还可以将其添加到您的 .htaccess 文件中:

AddDefaultCharset UTF-8

如果以上都不起作用,请在您的 PHP 代码中使用它(确保设置正确的位置):

setlocale(LC_ALL, 'fr_CA.utf-8');

看这里:http://php.net/manual/en/function.mail.php

【讨论】:

  • 谢谢,但不幸的是它也没有帮助...我唯一没有尝试的是将行添加到 .htaccess...
  • 试试 .htaccess。另外,我注意到您的 html 中有两个元标记,您只需要第二个。此外,您是否在 .html 中使用该表单?它应该是一个 .php,除非它们在同一个 .php 页面上。这可能会阻止它被发送。
  • 我有一个安装表单的 html(我的 index.html),然后我有我的 processform.php,我有 html 代码和 php 代码...
  • 我的文件夹中没有任何 .htaccess 文件...如果我创建一个,您的代码是否足够?
  • 是的。这就是你所需要的,它不需要其他必要的代码来实现这些目的。
【解决方案4】:

您可以尝试使用此 PHP 函数转换您想要显示的文本。 它以 UTF8 编码的字符串作为参数,并返回转换为 ISO-8859-1 字符的字符串

utf8_decode($your_text)

【讨论】:

  • 谢谢,但您不理解我的问题...我自己的文本没有问题,消息正文看起来不太好,我的访问者通过我的联系表发送...我不能在我收到的邮件中正确阅读我的消息...
猜你喜欢
  • 1970-01-01
  • 2013-01-24
  • 2011-12-21
  • 2015-01-15
  • 1970-01-01
  • 2011-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多