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
Related
I'm trying to send a message to the email a user provides in the contact form. The problem is the message never gets sent, but I always arrive at a blank page where my php code is located. Nothing warns me of any error in my code. Can anyone explain why this is happening and offer a solution to the problem?
<form action="site.php" method="POST">
<input
type="text"
class="form"
name="email"
placeholder="Your email address"
/>
<button class="submit" type="submit">Join Waitlist</button>
</form>
<?php
if (isset($_POST["submit"]))
{
$mailTo = $_POST["email"];
$mailFrom = "Dumele";
$message = "https://docs.google.com/forms/d/1lpj2XnKW4HT_qHFfGwpUxcvzPmK2USZ0MGSDP0XCqfg/edit";
$subject = "Welcome to Dumele";
$txt = "Thank you for your interest in Dumele. We're glad to have
you join our network and mission to enhance the technological
innovation of our African diaspora. Below is a link to a survey
we would like you to answer so we can better assist you.\n\n".message;
$headers = "From: ".mailFrom;
(mail($mailTo, $subject, $txt, $headers));
header("Location: index.php?mailsend");
}
?>
First of all make sure you enabled error reporting. You can check another Stackoverflow question and it's answers here about it.
As I see in your code you have syntax errors. You didn't place $ sign before variable names. For example you typed $headers = "From: ".mailFrom; instead of $headers = "From: ".$mailFrom; Let's fix it:
<?php
if (isset($_POST["submit"]))
{
$mailTo = $_POST["email"];
$mailFrom = "Dumele";
$message = "https://docs.google.com/forms/d/1lpj2XnKW4HT_qHFfGwpUxcvzPmK2USZ0MGSDP0XCqfg/edit";
$subject = "Welcome to Dumele";
$txt = "Thank you for your interest in Dumele. We're glad to have
you join our network and mission to enhance the technological
innovation of our African diaspora. Below is a link to a survey
we would like you to answer so we can better assist you.\n\n".$message;
$headers = "From: ".$mailFrom;
(mail($mailTo, $subject, $txt, $headers));
header("Location: index.php?mailsend");
}
Now with the mail() function of PHP; some servers disables mail() function for security purposes. If so; you can use SMTP to securely send your emails. To use SMTP in PHP of course you need additional processes but some free software packages and libraries like PHPMailer or SwiftMailer can help you about it.
This is looking for a form value with the name "submit":
if (isset($_POST["submit"]))
But there's no form element in the HTML with that name. So this will always be false. Give your submit button that name:
<button class="submit" type="submit" name="submit">Join Waitlist</button>
It shouldn't necessarily need a value, it would just default to an empty string. But it needs a name in order for the browser to send anything at all with that key.
As an aside, your mail server may reject the message since this is not really an email address:
$mailFrom = "Dumele";
For completeness... It looks like your PHP variables are also syntactically incorrect. Variable names need to begin with a $. For example, this:
$headers = "From: ".mailFrom;
Should be this:
$headers = "From: ".$mailFrom;
The same error would need to be corrected anywhere you're mis-using variable names.
Use value attribute in button tag. You are testing
if(isset($_post['submit']))
But what is submit? You should use value attribute and give a value submit i.e. Submit
I use php to send an email reseting a password.
<?php session_start(); ?>
<?php
if($_POST['UserEmail'] == '')
{
$_SESSION['error']['UserEmail'] = "E-mail is required.";
}
else
{
//whether the UserEmail format is correct
if(preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9._-]+)+$/", $_POST['UserEmail']))
{
//if it has the correct format whether the UserEmail has already exist
$UserEmail= $_POST['UserEmail'];
$to = $UserEmail;
$subject = "Forgotten Password";
$header = "Change your password using the link below";
$message = "http://www.yourname.com/confirm.php?UserEmail=$UserEmail&5832572895237532897523875";
$sentmail = mail($to,$subject,$message,$header);
}
}
?>
I want the $message to be a clickable link how do i do this.
This is using WAMPs default mailing system.
cheers
I Have tried adding an anchor tag but that sends the anchor aswell not just the clickable link
using
$Message="<a href=http://www.yourname.com/confirm.php?UserEmail=James#email.co.uk&5832572895237532897523875>click here</a>" Doesnt work either any suggestions
Fix Found
basically it was fine just leaving the link in without any anchor tags.
$message="http://www.sitename.com/this.php?Username=email#email.com&432941482401284"
will display a clickable link inside your email.
Sorry for that
use anchor tag to make it clickable and assing it to $message:-
$message= "<a href='http://www.yourname.com/confirm.php?UserEmail=".$UserEmail."&5832572895237532897523875'>Click Here</a>";
$header is the mail-header containing non-display-values.
for example:
From: Your Name <you#example.com>\r\n
Reply-To: Max Muster <max#example.com>\r\n
(\r\n are the escaped characters)
There you also set the content-type:
Content-Type: text/html; encoding: utf-8\r\n
With this you can use html to design your mail and use <a>-tags for your links.
More Information: http://en.wikipedia.org/wiki/Email#Message_Header (Or if you are German: http://de.wikipedia.org/wiki/Header_(E-Mail) )
Everything, that does not belong to the header described in that links, has to be in the message-content, so in your $message. That includes your "click on that link below".
For address-checking take a look at http://php.net/manual/de/function.filter-var.php
A client recently got a spam warning from their host.
I think I have pin pointed the issue to an old contact us form. Simple html on the front end and a simple PHP script on the back end.
if ($_POST['submit'] == "Send"){
//START SEND MAIL SCRIPT
$mail = $_POST['email'];
$to = "me#gmail.com";
$subject = "Message from Website Contact Us Form";
$headers = "From: Contact us Form <webmaster#website.co.uk>";
$message = "Message from Contact Us Form\n\n";
$message .= "\nName: " . $_POST['contactname'];
$message .= "\nEmail: " . $_POST['contactemail'];
$message .= "\nTelephone: " . $_POST['contactphone'];
$message .= "\n\n\nMessage:\n" . $_POST['contactmessage'];
if(mail($to,$subject,$message,$headers)) {
header('Location: http://www.website.co.uk/contact-us/?action=success');
}else{
header('Location: http://www.webisite.co.uk/contact-us/?action=fail');
}//END IF MAIL
}//END SCRIPT
I know the remedies to fix it such as sanitizing post vars properly, using captchas, using a hidden 'honeypot' blank field, js tricks etc etc (I also like the look of this script too http://www.alt-php-faq.com/local/115/)
But to help me understand what was going on I want to know how this script is being manipulated. A foreign script posting vars to it but how do they send email to anyone apart from
'me#gmail.com' or if they are forcing cc / bcc fields somehow why do I not get all spam as well??
Thanks
Line like this $message .= "\nName: " . $_POST['contactname']; can be dangerous.
If $_POST['contactname']='MegaSteve4 \r\nCc: email1#mail.com, email2#mail.com'; are set, 2 uses will get spam mail.
See carefully. Its appending more headers. In this case Cc. I am not sure if Cc is a raw email header. But I hope you get the idea.
You're not doing any escaping of the post data. That means that this form is vulnerable to injection attacks.
I couldn't tell you how they did it, but that's probably what happened.
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.
I have a simple PHP mailer script that takes values from a form submitted via POST and mails them to me:
<?php
$to = "me#example.com";
$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];
$body = "Person $name submitted a message: $message";
$subject = "A message has been submitted";
$headers = 'From: ' . $email;
mail($to, $subject, $body, $headers);
header("Location: http://example.com/thanks");
?>
How can I sanitize the input?
Sanitize the post variable with filter_var().
Example here. Like:
echo filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Since you're not building an SQL query or anything here, the only relevant validation that I can see for those inputs is an email validation for $_POST["email"], and maybe an alphanumeric filter on the other fields if you really want to limit the scope of what the message can contain.
To filter the email address, simply use filter_var:
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
As per Frank Farmer's suggestion, you can also filter out newlines in the email subject:
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
As others have noted, filter_var is great. If it's not available, add this to your toolchest.
The $headers variable is particularly bad security-wise. It can be appended to and cause spoofed headers to be added. This post called Email Injection discusses it pretty well.
filter_var is great, but another way to assure that something is an email address and not something bad is to use an isMail() function. Here's one:
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
So to use this, you could do:
if (isset($_POST['email']) && isEmail($_POST['email'])) {
$email = $_POST['email'] ;
} else {
// you could halt execution here, set $email to a default email address
// display an error, redirect, or some combination here,
}
In terms of manual validation, limiting the length using substr(), running strip_tags() and otherwise limiting what can be put in.
You need to remove any newlines from input provided by users in $headers, which gets passed to mail() ($email in your case)! See Email injection.
PHP should take care of sanitizing $to and $subject, but there are versions of PHP with bugs (Affected are PHP 4 <= 4.4.6 and PHP 5 <= 5.2.1, see MOPB-34-2007).
You can use the code from artlung's answer above to validate email..
I use this kind of code to prevent header injection ..
// define some mail() header's parts and commonly used spam code to filter using preg_match
$match = "/(from\:|to\:|bcc\:|cc\:|content\-type\:|mime\-version\:|subject\:|x\-mailer\:|reply\-to\:|\%0a|\%0b)/i";
// check if any field's value containing the one or more of the code above
if (preg_match($match, $name) || preg_match( $match, $message) || preg_match( $match, $email)) {
// I use ajax, so I call the string below and send it to js file to check whether the email is failed to send or not
echo "failed";
// If you are not using ajax, then you can redirect it with php header function i.e: header("Location: http://example.com/anypage/");
// stop the script before it reach or executing the mail function
die();
}
The mail()'s header filtering above is too strict, since some users may be using the filtered strings in their message without any intention to hijack your email form, so redirect it to a page that is explaining what kind of strings that is not allowed in the form or explain it on your form page.