簡體   English   中英

PHP聯系人消息中的特殊字符(utf-8)

[英]Special characters (utf-8) in PHP contact message

我有聯系表格。 當我收到一條消息時,我無法正常閱讀,因為特殊字符會顯示出來。

我在utf-8中保存了我的文件,沒有BOM,我紅了,嘗試了很多關於這個主題的變化,但我找不到適合自己的答案。

我的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文件(以無BOM的UTF-8保存)具有以下代碼:

<?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;
}

?>

嘗試將此行添加到標題中,

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

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

您可以嘗試使用此PHP函數轉換要顯示的文本。 它將UTF8編碼的字符串作為參數,並返回以ISO-8859-1字符轉換的字符串

utf8_decode($your_text)

由於您使用的是UTF-8,請考慮使用php多字節函數鏈接mb_ *。 例如:

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

您可能感興趣的其他mb_ *函數:

strrpos()mb_strrpos()

substr()mb_substr()

有關多字節功能的完整列表,請查看此處

如果您不想在每個mb_函數中傳遞'UTF-8',請在腳本的開頭調用mb_internal_encoding('UTF-8')

要使mail()函數與UTF-8一起正常工作,請在標題中傳遞以下內容:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM