Special characters (utf-8) in php contact message
I have a contact form. When I receive the message, I cannot read it normally because the special characters are shown strangely.
I saved my file in utf-8 without BOM, I am red and tried many variations on this but I could not find the correct answer for myself.
Contact form in my 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>
My processform.php file (saved in UTF-8 without BOM) has the following codes:
<?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écurité indiqué est incorrect.<br />";
echo "Rafraîchissez la page et essayez à 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 été envoyé avec succè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;
}
?>
source to share
Since you are using UTF-8, consider using the multibyte php link mb_
* functions . For example:
echo strlen('è'); // output 2
echo mb_strlen('è', 'UTF-8'); // output 1
Other mb_ * functions that might interest you:
strrpos()
before mb_strrpos()
substr()
before mb_substr()
For a complete list of multibyte functions take a look here .
If you don't want to pass "UTF-8" in every mb_ function, call it mb_internal_encoding('UTF-8')
at the beginning of your script.
For the function to work mail()
correctly with UTF-8, pass the following in the header:
$header = "Content-Type: text/html; charset=UTF-8"
source to share
1-Make sure it's HTML in your head:
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
2-Then add this to the top of your PHP script:
header('Content-Type: text/html; charset=utf-8');
An example of the first two steps:
<!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>
As an alternative to step 2, you can add this to your .htaccess file:
AddDefaultCharset UTF-8
If none of the above is used then use this in your PHP code (remember to set the correct location):
setlocale(LC_ALL, 'fr_CA.utf-8');
Take a look here: http://php.net/manual/en/function.mail.php
source to share