0

I have little problem with contact form. When I send a message, subject and sender name does not display special characters. Message box display special characters correct. I set UTF-8, so I think it should work for all fields. I have no idea.

My PHP code:

define( "RECIPIENT_NAME", "My name" );
define( "RECIPIENT_EMAIL", "info@domain.com" );

$success = false;
$senderName = isset( $_POST['username'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['username'] ) : "";
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email'] ) : "";
$subject = isset( $_POST['subject'] ) ? preg_replace( "/[^\.\-\' a-zA-Z0-9]/", "", $_POST['subject'] ) : "";
$message = isset( $_POST['message'] ) ? preg_replace( "/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message'] ) : "";

if ( $senderName && $senderEmail && $subject && $message) {
  $recipient = RECIPIENT_NAME . " <" . RECIPIENT_EMAIL . ">";

  /* $headers = "From: " . $senderName . " <" . $senderEmail . ">"; */

  $headers = 'From:'.$senderName.' <'.$senderEmail.'>' . "\r\n";
  $headers .= "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";


  $msgBody = "From: " . $senderName . "<br><br>Message:<br>" . $message;
  $success = mail( $recipient, $subject, $msgBody, $headers );


  header('Location: contact.php');
}

else {
    header('Location: index.php');  
}
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
Raphael
  • 11
  • 2
  • Your if statement is redundant – Rotimi Nov 24 '18 at 19:12
  • There are a few types of UTF-8 (file encoding); which one did you use to save the file(s) as? – Funk Forty Niner Nov 24 '18 at 19:12
  • All it takes, is one wrong charset setting in your application - *everything* needs to be the same charset! I have previously written [**an answer about UTF-8 encoding**](https://stackoverflow.com/a/31899827/4535200) that contains a little checklist, that will cover *most* of the charset issues in a PHP/MySQL application. There's also a more in-depth topic, [**UTF-8 All the Way Through**](https://stackoverflow.com/q/279170/4535200). Most likely, you'll find a solution in either one or both of these topics. – Qirel Nov 24 '18 at 19:22
  • I recommend you use something like PHPMailer to send mail instead of using `mail()`. – Qirel Nov 24 '18 at 19:24
  • I don't understand why message content display special characters correct, but subject and sender name not? – Raphael Nov 24 '18 at 19:29

0 Answers0