Utf8 encoding in php [duplicate] - php

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 1 year ago.
I am getting some data from a html form and sending them by email with PHP.
The issue is that i am getting weird characters because the language that the user writes in the form is Czech.
For example the name Anežka becomes Anežka
This is the code i have for my php which being used for sending the email.
<?php
if(isset($_POST['submit'])){
$to_alex = "myemail#honeywell.com"; // this is your Email address
$first_name = $_POST['fname'];
$first_name=mb_convert_encoding($first_name, "UTF-8", "ISO-8859-1");
$last_name = $_POST['lname'];
$email = $_POST['email'];
$skola = $_POST['vysoka_skola'];
$obor = $_POST['obor'];
$prace = $_POST['prace'];
$phone_num=$_POST['phone_number'];
$linkedin=$_POST['linkedin'];
$oponenta=$_POST['oponenta'];
$vedouciho=$_POST['vedouciho'];
$files = $_FILES['myfile']['name'];
$kategorie = $_POST['kategorie'];
//echo gettype($files);
$all_thesis_string="";
$all_vedouciho_string="";
for($index=0;$index<count($_FILES['myfile']['name']);$index++){
$all_thesis_string.=$_FILES['myfile']['name'][$index].","; //create a string with all bachelor attachments of user
}
for($index=0;$index<count($_FILES['vedouciho_files']['name']);$index++){
$all_vedouciho_string.=$_FILES['vedouciho_files']['name'][$index].","; //create a string with all vedouciho attachments of user
}
for($index=0;$index<count($_FILES['oponenta_files']['name']);$index++){
$all_vedouciho_string.=$_FILES['oponenta_files']['name'][$index].","; //create a string with all oponenta attachments of user
}
$subject = "Form submission of ".$first_name." ".$last_name;
$message = "User Details: \n\n Jméno: $first_name \n Příjmení: $last_name \n Email: $email \n Telefon: $phone_num \n Linkedin: $linkedin \n Vysoká škola: $skola \n Studijní obor: $obor \n Odkaz na bakalářskou práci: $prace \n Kategorie: $kategorie \n Posudek oponenta: \n $oponenta \n Posudek vedouciho: \n $vedouciho \n Bakalářská práce: $all_thesis_string \n Vedouciho files: $all_vedouciho_string";
$headers = "From:" . $first_name;
mail($to_alex,$subject,$message,$headers);
echo '<span style="color:#AFA;text-align:center;"><strong>"Přihláška úspěšně odeslána. Děkuji "</strong></span>';
//include 'upload.php';
// You can also use header('Location: thank_you.php'); to redirect to another page.
}
?>
I have tried mb_convert_encoding in my last attempt but still i have the issue.

You need to tackle possible issues on both input and output stages of your program:
make sure, the browser knows, that you want UTF-8: It needs the tag <meta charset="utf-8"> somewhere in the <head> of your HTML. Otherwise it is possible, that it falls back to some legacy encoding when sending form data back to you.
make sure, e-mail clients know, that you send UTF-8 to them. They, too, will fall back to legacy encodings without explicitly telling them. Try adding these headers to the mail:
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable
If you want UTF-8 in the subject and/or To fields, you need a separate way of quoting. I suggest you take a look at the excellent PHPMailer package that will handle all that for you.

Related

Convert escaped characters PHP [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I know this is a simple question, but having a hard time finding a simple solution.
I have a form on my PHP site that takes in the user message, then sends an email to my client with the message. I want the message sent to my client to be easily readable, without escaped characters \r , \n , \" , etc.
For example, the message is currently coming into the email as:
test\'s\r\nnew line \r\n\"quote\"
What I want it to come in as:
test's
new line
"quote"
Current code is:
if(isset($_POST['submit']) && !empty($_POST['email'])){
//Process form
$name = $_POST['name'];
$name = mysql_prep($name);
$email = $_POST['email'];
$email = mysql_prep($email);
$message = $_POST['message'];
$message = mysql_prep($message);
$emailto = "client_email1#gmail.com,client_email2#gmail.com";
$subject = "Message from '$name'";
// the message
$message = "<html><body>
<h3>Title</h3>
From: $name<br>
Email: $email<br><br>
Message:<br>
$message<br><br>
</body></html>";
//headers make the mail() work
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
mail($emailto, $subject, $message, $headers);
What you need is stripslashes() and nl2br().
nl2br will make newlines html br tags.
Stripslashes does what the name indicates, it removes slashes that is escape slashes.
echo stripslashes(nl2br($str));
Example: https://3v4l.org/RPYWt
Couple issues, first was my $message = mysql_prep($message); function was creating the escaped characters, so I just put that function after the mail() function. mysql_prep() was used to prevent mysql injection.
Second, I needed the $message = nl2br($message) function to maintain the user entered new lines from the form so the client can see the message as it was typed. I put the nl2br() function just after the $message = $_POST['message']; line.

Ajax contact form and UTF-8

i'm using ajax contact form, downloaded from: http://youhack.me/2010/07/22/create-a-fancy-contact-form-with-css-3-and-jquery/
Everything works ok except UTF as i can't use cyrilic symbols when submitting.
The php:
$name = $_POST['name']; // contain name of person
$email = $_POST['email']; // Email address of sender
$web = $_POST['web']; // Your website URL
$body = $_POST['text']; // Your message
$receiver = "receiver#domain.com" ; // hardcorde your email address here - This is the email address that all your feedbacks will be sent to
if (!empty($name) & !empty($email) && !empty($body)) {
$body = "Name: {$name}\n\nSubject: {$web}\n\nMessage: {$body}";
$send = mail($receiver, 'Contact from domain.com', $body, "From: {$email}");
if ($send) {
echo 'true'; //if everything is ok,always return true , else ajax submission won't work
}
}
It uses jquery.validationEngine-en for validation.
My html already has "Content-Type" content="text/html; charset=utf-8" in header.
I'm new to php and jquery, so i would appriciate some guidance to make UTF-8 work when submitting.
Thanks :)
Edit: When i try to use cyrilic chars (čšćđ) on a required field i get ajax input error "Please use letters only". If i submit the form with cyrilic chars on a non-required field, i receive and email, all letters show ok except cyrilic, which are like this: Å¡.
Edit 2: When i set the recipient to gmail (webmail), cyrilic chars show up ok, except in one field, where Ajax doesnt let me use them (regex from Reinder answer).
When i set recipient in outlook (local) and submit the form, none of the cyrilic chars don't show up ok, example: ÄĹĄ oÄa ĹĄ ÄŽŠÄÄ
SOLVED Thanks to Reinder for guide and David! Will solve it today :)
having looked at the plugin you're using, I think this has to do with the validation regex inside jquery.validationEngine-en.js
when the validation is set to 'onlyLetter' it will check using
/^[a-zA-Z\ \']+$/
and none of your characters čšćđ are allowed here...
you need to create a language validation javascript for the language you're using and change that regular expression. For example, have a look at this post
The next thing is to check the encoding of your PHP file and your headers.
Place this at the top of your PHP code
header("Content-type: text/html; charset=utf-8");
Check if the values are correctly displayed when just outputting them in PHP, like so:
echo $name;
If they are correctly displayed in the browser and it's just the email that's incorrectly displaying the characters, then you need to pass an encoding header to the email too
example:
$headers = "From: $name <$email>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$body = "Name: {$name}\n\nSubject: {$web}\n\nMessage: {$body}";
$send = mail($receiver, 'Contact from domain.com', $body, $headers);
have a look at the mail function on the PHP.NET website
Rather than use the default PHP mail() function, I've found this come in handy when working with Japanese:
http://bitprison.net/php_mail_utf-8_subject_and_message

Secure php email script

I want to use a php script to send emails from a html file on a website.
Would this php script be secure enough against hacking and spam?
<?php
$to = "emailto#site.com";
$subject = "Sent from site";
$email = $_POST['emailFrom'];
$message = $_POST['message'];
$email = filter_var($email , FILTER_SANITIZE_EMAIL);
$message = filter_var($message , FILTER_SANITIZE_EMAIL);
$message = $email . $message;
mail($to, $subject, $message, "From: webpage#site.com");
?>
FILTER_SANITIZE_EMAIL removes illegal email address characters from a string; this is, therefore not the best option for the contents of an email (however useful it may be for email addresses). Whilst removing HTML special characters is useful when preventing XSS attacks, it is worth noting that there are legitimate reasons to post < and > in messages (i.e. right now). Therefore it is better to convert these characters to their html entities.
I.e.
< would become <
and > would become >
So in order to change html characters to their entities replace:
$message = filter_var($message , FILTER_SANITIZE_EMAIL); with
$message = htmlspecialchars($message);
Other than that it looks good; but remember, in cases where a database is involved database sanitisation should also be added.

PHP Mail: special characters show different between Firefox and IE

I have a problem when sending a form via email using the PHP Mail function. This is the code that I'm using:
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$company = $_POST['company'];
$email = $_POST['email'];
$country = $_POST['country'];
$phone = $_POST['phone'];
$message = $_POST['message']); //This comes from the form
$formcontent="Name: $name $last_name <br> Company: $company <br> Email: $email <br> Country: $country <br> Telephone: $phone <br><br> Message: $message";
$mailheader = 'MIME-Version: 1.0' . "\r\n";
$mailheader .= 'Content-type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable' . "\r\n";
$mailheader .= 'From: ' . $email . "\r\n";
mail("my#email.com", "subject", $formcontent, $mailheader) or die("Error!");
This is a form that will be sending spanish and special characters, like ñ, accents, ç, etc...
The problem is that, if I use it like this, it works fine in Firefox 3.6.3, but when using the form in Internet Explorer 8, the special characters that sends are all messed up (like ç instead of a ç). However, if I add utf8_encode to the variables in the $formcontent, then it works in IE, but it stops working in Firefox, showing stuff like η instead of ç.
What can I do to make it work regardless of the browser? Any help would be much appreciated!
EDIT:
I've noticed that, if I echo the $formcontent variable before sending it with mail, if I'm using Firefox, the special characters are already messed-up. How can I avoid the browsers interfering with what's being sent? Please I'm totally clueless right now!!! I don't know what to change to have something working. Even if it's a dumbed down version, is there any alternative to have PHP Mail working with special characters in both browsers?
Basically you need to make sure that every charset on your page is the same. Make sure the page has a utf-8 charset aswel. Since you're sending it in utf8 the input must come from utf8 aswell.
Could you perhaps show us the code of the page (or a live demo) where the mail is being made?

PHP and Russian Letters

What is happening with Russian letters when sending via PHP request to ... a mail, by e.g.?
the "hardcoded" russians letters are displayed properly, but from the Form's textboxex with hieroglyphs:
HTML page:
<tr>
<td style="width: 280px">Содержание работ</td>
<td><input type="text" id="workContent"/></td>
</tr>
PHP page:
$WorkContent = $_REQUEST["workContent"]; //Содержание работ
// ...
$WorkContentLabel = "Содержание работ";
// ...
$message .= $WorkContentLabel . ":\t" . $WorkContent . "\n";
// ...
// email stuff (data below changed)
$to = "test#gmail.com";
$from = "me#domain.com";
$from_header = "From: Russian site command ";
$subject = "Message with russian letters";
$subject = '=?utf-8?B?'.$subject.'?=';
$message .= $subject;
// send message
mail($to, $subject, $message, $from_header);
User enter some content in the textbox:
alt text http://lh3.ggpht.com/_1TPOP7DzY1E/S1y6Y0wb9tI/AAAAAAAAC88/OkdMQkO47HQ/s800/works.png
and the submits the form.
What do I receive (in GMAIL):
Содержание работ: 1)Содержание 2)RABOT
So, hard-coded Russian text - OK, sent by the form Russian text - NOK, sent by the form ASCII text - OK.
Does somebody know what could be the cause of that strange behavior with the encoding?
EDIT:
used
$subject = " оборудования - subject with russian letters";
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
$message .= $subject;
obtains a subject like
�����������ÿ - subject with russian letters http://lh6.ggpht.com/_1TPOP7DzY1E/S1zFqFe9ohI/AAAAAAAAC9E/PZ7C4JtEHTU/s800/subject.png
You need to base64_encode() your $subject, like this:
$subject = '=?UTF-8?B?' . base64_encode($subject) . '?=';
Make sure you're also saving your .php file encoded as UTF-8 no BOM.
This question might also interest you: Is this the correct way to send email with PHP?
Check your encodings:
HTML encoding (in the <meta http-equiv..> tag)
PHP/HTML/template file encoding (what encoding your editor saves the file in)
Database encoding (if applicable) (in what encoding the data in the tables is in)
Database connection encoding (if applicable) (what encoding is used for database connections)
and use UTF-8 for everything.
As well as what Alix said about base64 in the RFC2047 encoded-word in your Subject line, you also need to tell the mailer to expect UTF-8-encoded text in the body of the mail, by adding headers:
MIME-Version: 1.0
Content-Type: text/plain;charset=utf-8
otherwise it's up to the mailer to guess, probably wrongly.

Categories