How to validate email address [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to validate an email address in PHP
I was wondering someone can help me please.
I need to validate the email address for the below code but am having problems.
<?php
if ($_POST) {
$expected = array('name', 'email', 'emailmessage');
$validation = array(
'name' => 'Please provide your full name',
'email' => 'Please provide your valid email address',
'emailmessage' => 'Please provide message'
);
$errors = array();
$output = array();
foreach($expected as $key) {
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
if (empty($_POST[$key])) {
$errors[$key] = $validation[$key];
} else {
$output[$key] = $_POST[$key];
}
} else {
$errors[$key] = $validation[$key];
}
}
if (!empty($errors)) {
$array = array('error' => true, 'fields' => $errors);
} else {
// PROCESS FORM
// ---------------------------------------------------------
// BEGIN EDITING
// ---------------------------------------------------------
$to = "qakbar#hotmail.co.uk"; //This is the email address messages will be sent to
$web_name = "My Test Web Form"; //This is the name of your website that will show in your email inbox
//get IP address
$ip = $_SERVER['REMOTE_ADDR'];
//make time
$time = time();
$date = date("r", $time);
// ---------------------------------------------------------
// END EDITING
// ---------------------------------------------------------
$emailmessage = trim($emailmessage);
$emailmessage = nl2br($emailmessage);
$emailmessage = htmlspecialchars($emailmessage);
$emailmessage = wordwrap($emailmessage, 70);
//Visible form elements
$name = $_POST['name']; //Sender's name
$email = $_POST['email']; //Sender's email
$emailmessage = htmlspecialchars($_POST['emailmessage']); //Sender's message
//Setting up email
$subject = "New Message from $web_name";
$message = "
New message from $name <br/><br/>
Message:<br />
$emailmessage
<br/>
<br/>
Email: $email<br />
IP:</strong> <span style=\"color:#990000;\">$ip</span><br />
Date:</strong> $date
";
$header = 'MIME-Version: 1.0' . "\r\n";
$header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$header .= 'From:'. $email . " \r\n";
$sent = mail($to, $subject, $message, $header);
//$message = '<div id=message>You have successfully subscribed to our newsletter</div>';
$array = array('error' => false, 'message' => $message);
}
echo json_encode($array);
}
I want the email to validate in the $validation array as my messages are passed through this and need the email validation to do the same.
I was trying to use the following but did not know where to place it or how to call it.
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// email is valid
} else {
// email is invalid
}
Any help is much apprecaited.
Thank you

You could use it like this:
filter_var($email, FILTER_VALIDATE_EMAIL) or die("Email wrong.");
Right after you assigned this exact variable:
$email = $_POST['email'];
Of course this could be structured more sensible, and a nicer error notice would also be possible. But it sounds as if you need more general practice with PHP first.

An oddity with your code:
$input = htmlspecialchars($_POST[$key]);
if (array_key_exists($key, $_POST)) {
You're using the key already BEFORE checking if it exists. As well, the $input variable is not used again in your code, so it's a useless line.

May be, this code will help you. try it.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['uname'];
$email = $_POST['email'];
$valid_arr = array();
$error_arr = array();
if($name == ''){
$error_arr['name'] = 'Required';
}
else if(!preg_match('/^[a-zA-A]+$/',$name)){
$error_arr['name'] = 'Please put correct value';
}
else{
$valid_arr['name'] = $name;
}
if($email == ''){
$error_arr['email'] = 'Required';
}
else if(!preg_match('/^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/',$email)){
$error_arr['email'] = 'Exm.- john#gmail.com';
}
else{
$valid_arr['email'] = $email;
}
if(count($error_arr) == 0){
header('location: success.php');
}
else{
echo 'Error in Loading';
}
}
?>
<html>
<head>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF'];?>" method="POST">
<table>
<tr>
<td><label>User Name :</label></td>
<td><input type="text" name="uname" value="<?php echo $valid_arr['name'];?>"/></td>
<td class="error"><?php echo $error_arr['name'];?></td>
</tr>
<tr>
<td><label>Email :</label></td>
<td><input type="text" name="email" value="<?php echo $valid_arr['email'];?>"/></td>
<td class="error"><?php echo $error_arr['email'];?></td>
</tr>
<tr>
<td><input type="submit" name="save" value="Submit"/></td>
</tr>
</table>
</form>
</body>
</html>

Related

contact form not giving data

I have issue with fat-free contact form.
My contact form does nothing. Like no success or any kind of error data.
My contact form POST and GET route:
$f3->route('GET #contact: /contact', 'Rimtay\Client->GET_Contact');
$f3->route('POST #contact: /send', 'Rimtay\Client->contactPost');
My contact form POST function:
function contactPost(){
function validateInput($data) {
$bad = array("content-type","bcc:","to:","cc:","href");
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
foreach ($bad as $badString) {
if (preg_match('/('.$badString.')/i',$data)) {
// If it looks like someone is trying to hack
// into the site via the contact page, then just stop.
exit;
}
}
return $data;
}
// define variables and set to empty values
$contactNameError = $contactEmailError = $contactMessageError = "";
$name = $email = $message = $success = "";
if ($f3->exists('POST.name',$name)) {
if ($name !== '') {
$name = validateInput($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$contactNameError = "Wrong name";
} else { // valid name
$f3->set('contactName',$name);
}
} else {
$contactNameError = "name empty";
}
} else {
$contactNameError = "name error";
}
if ($f3->exists('POST.email',$email)) {
if ($email !== '') {
$email = validateInput($email);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailError = "wrong email";
} else { // valid email
$f3->set('contactEmail',$email);
}
} else {
$contactEmailError = "email empty";
}
} else {
$contactEmailError = "error email";
}
if ($f3->exists('POST.subject',$message)) {
if ($message !== '') {
$f3->set('contactMessage',$message);
} else {
$contactMessageError = "message tühi";
}
} else {
$contactMessageError = "lambi message";
}
if (($contactNameError === '') && ($contactEmailError === '') && ($contactMessageError === '')) {
// send the message
$messageBody = "";
unset($_POST['submit']);
$messageBody = "Name: ".$name."\n";
$messageBody .= "email: ".$email."\n";
$messageBody .= "Subject: Construction - Message from " . $name."\n";
$messageBody .= $message."\n";
$messageBody = wordwrap($messageBody,70);
$to = $f3->get('contactAddresses');
$subject = 'Contact Submitted';
if (mail($to, $subject, $messageBody)){
$f3->set('contactSuccess',true);
} else {
// error sending the email to myself
}
} else {
$f3->set('contactSuccess',false);
}
// Set the content source
$this->f3->set('pageContent','contact.html');
}
my form looks like this:
<form class="form" action="{{ #schemeHost.#PATH }}" method="post">
<textarea class="textarea" name="message" placeholder="Message*">{{ #contactMessage }}</textarea>
<div>
<input type="text" placeholder="Name *" name="name" value="{{ #contactName }}" class="input">
<input type="email" placeholder="Email *" name="email" value="{{ #contactEmail }}" class="input">
</div>
<button class="submit" type="submit" name="submit">Send</button>
</form>
My System isnt giving any success or error messages.
And not sending out contact form messages to email.
I dont see what I'm doing wrong there.
Your code is very prone to errors. For example, the $f3 variable is not defined anywhere in your code.
How does your code handle the errors? It might be that you see no errors because there is no error reporting setup by you and the server is silently not showing the errors. I suggest you to check the error log.
I also suggest to use a form validation library like CakePHP validation library. You will need to learn how to use it, but it will save you big time in the end and your code will be cleaner.

Select case with array

How can I write a select case with an array to check form validation?
this is my code:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
switch($array[]) {
case empty($array[0]):
error = "name";
break;
case empty($array[1]):
error = "email";
break;
case empty($array[2]):
error = "message";
}
Then, I would like to write code to have this result:
if name is empty:
"Please fill in your name"
if email is empty:
"Please fill in your email"
if name and email is empty:
"Please fill your name and email"
if name and email and message is empty:
"Please fill in your name, email and message"
You want to concat your messages, so better use if statements:
$error = "Please fill in: ";
if (empty($array[0]))
$error .= "name ";
if (empty($array[1]))
$error .= "email ";
if (empty($array[2]))
$error .= "message ";
The .= will concat the string to the existing one.
Try this for a grammatically correct solution:
$empty = array();
$fields = array('name', 'email', 'message');
foreach ($fields as $key => $value){
if(empty($_POST[$value])) $empty[] = $value;
}
$error_msg = '';
$count = count($empty);
$cnct = ', ';
if ($count > 0){
$error_msg = 'Please fill in your ';
}
foreach ($empty as $key => $value){
if ($key == $count - 2){
$cnct = ' and ';
}elseif($key == $count - 1){
$cnct = '.';
}
$error_msg .= $value.$cnct;
}
You can simply try:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$error="Please fill in your ";
$array = array('name'=>$name,'email'=>$email,'message'=>$message);
foreach($array as $key=>$value){
if(empty($value)){
$error.=','.$key;
}
}
You can't use a variable expression in case statement of switch block.
A switch case must have a constant expression in many languages including php. So, something like a variable or function call doesn't work.
You better use conditionals for this.
Your code is also missing $ symbol for variable error.
Do this instead:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$array = array($name,$email,$message);
$error="Please fill in your ";
if(empty($array[0])){
$error.= "\nname";
}
if(empty($array[1])){
$error.="\nemail";
};
if(empty($array[2])){
$error.= "\nmessage";
}
echo $error;
You should simply write:
$error = "Please fill in: ";
if (empty($array[0]))
$error.= "name ";
if (empty($array[1]))
$error.= "email ";
if (empty($array[2]))
$error.= "message";
A switch isn't made for what you want to do.

Incorrect encoding with Cyrillic in PHP contact form

I'm new to using PHP and forms so if someone is willing to help, I'll be extremely grateful.
I have a contact form, but it doesn't send any Cyrillic characters correctly. I know that I have to put Content-type: text/plain; charset=UTF-8 somewhere in the code but I have no idea where to put it exactly. The form element is set to post in UTF-8, but it doesn't seem to work correctly with the PHP file.
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "myemailaddress#mail.com";
$from_email = "";
$continue = "index.php";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if (count($_COOKIE)) {
foreach(array_keys($_COOKIE) as $value) {
unset($_REQUEST[$value]);
}
}
// Validate email field.
if (isset($_REQUEST['email']) && !empty($_REQUEST['email']) && !empty($_REQUEST['family']) && !empty($_REQUEST['about'])) {
$_REQUEST['email'] = trim($_REQUEST['email']);
if (substr_count($_REQUEST['email'], "#") != 1 || stristr($_REQUEST['email'], " ")) {
$errors[] = "Email address is invalid";
} else {
$exploded_email = explode("#", $_REQUEST['email']);
if (empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])) {
$errors[] = "Email address is invalid";
} else {
if (substr_count($exploded_email[1], ".") == 0) {
$errors[] = "Email address is invalid";
} else {
$exploded_domain = explode(".", $exploded_email[1]);
if (in_array("", $exploded_domain)) {
$errors[] = "Email address is invalid";
} else {
foreach($exploded_domain as $value) {
if (strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i', $value)) {
$errors[] = "Email address is invalid";
break;
}
}
}
}
}
}
}
// Check referrer is from same site.
if (!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']))) {
$errors[] = "You must enable referrer logging to use the form";
}
// Check for a blank form.
function recursive_array_check_blank($element_value) {
global $set;
if (!is_array($element_value)) {
if (!empty($element_value)) {
$set = 1;
}
} else {
foreach($element_value as $value) {
if ($set) {
break;
}
recursive_array_check_blank($value);
}
}
}
recursive_array_check_blank($_REQUEST);
if (!$set) {
$errors[] = "You cannot send a blank form";
}
unset($set);
// Display any errors and exit if errors exist.
if (count($errors)) {
foreach($errors as $value) {
print "$value<br>";
}
exit;
}
if (!defined("PHP_EOL")) {
define("PHP_EOL", strtoupper(substr(PHP_OS, 0, 3) == "WIN") ? "\r\n" : "\n");
}
// Build message.
function build_message($request_input) {
if (!isset($message_output)) {
$message_output = "";
}
if (!is_array($request_input)) {
$message_output = $request_input;
} else {
foreach($request_input as $key = > $value) {
if (!empty($value)) {
if (!is_numeric($key)) {
$message_output. = str_replace("_", " ", ucfirst($key)).
": ".build_message($value).PHP_EOL.PHP_EOL;
} else {
$message_output. = build_message($value).
", ";
}
}
}
}
return rtrim($message_output, ", ");
}
$message = build_message($_REQUEST);
$message = $message.PHP_EOL.PHP_EOL.
"-- ".PHP_EOL.
"Thank you for using the contact form.";
$message = stripslashes($message);
$subject = $_REQUEST['about'];
$subject = stripslashes($subject);
if ($from_email) {
$headers = "From: ".$from_email;
$headers. = PHP_EOL;
$headers. = "Reply-To: ".$_REQUEST['email'];
} else {
$from_name = "";
if (isset($_REQUEST['name']) && !empty($_REQUEST['name'])) {
$from_name = stripslashes($_REQUEST['name']);
}
$headers = "From: {$from_name} <{$_REQUEST['email']}>";
}
mail($my_email, $subject, $message, $headers); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Your mail has been sent!</title>
<meta http-equiv="Content-Type" content="text/html; charset = utf - 8 ">
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<center>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<br>Your mail has been sent!
<p>Click here to continue</p>
</center>
</div>
</body>
</html>
Добави това:
$headers = "From: " . $from_email;
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
//новия код (new code)
$headers .= "MIME-Version: 1.0"."\r\n" ."Content-type: text/plain; charset='utf-8'". "\r\n";
Няма да е лошо да сложиш и някаква форма на верификация (картинка с код примерно, който трябва да се въведе, т.нар. CAPTCHA code) преди пращане от юзера, иначе всеки спам бот ще ти ползва формата за пращане на мейли, порови тук има доста начини за справяне с проблема.
Translated: (It is not bad idea to put some sort of verification code, an image with code inside of it, a so called CAPTCHA before sending the email, because otherwise every spam bot from Internet will use your form for mailing, check here for more ways to deal with the problem.)

Checkbox value not displaying

The form inputs aren't displaying on the form.php page and negates my form validation. The error says undefined variable for all my variables on form.php. Please tell me what I have to edit in my code to make it display the form inputs on form.php. It works when I use it on the same page but I would rather it display on another page.
EDIT
Thanks so far but I can't get the value of the checkbox, the recipient(Administrator or Content Editor), to display it displays "Array" or "A".
contact.php
<?php
$errnam = "";
$errmail = "";
$errsub = "";
$errrec = "";
$hasErrors = false;
if(isset ($_POST['submitted'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$recipient = $_POST['recipient'];
$message = $_POST['message'];
if(preg_match("/^[\w\-'\s]/", $_POST['name'])){
$name = $_POST['name'];
}
else{
$errnam ='<strong>Please enter a name.</strong>';
$hasErrors = true;
}
if (preg_match("/^[\w.-_]+#[\w.-]+[A-Za-z]{2,6}$/i", $email)){
$email = $_POST['email'];
}
else{
$errmail = '<strong>Please enter a valid email.</strong>';
$hasErrors = true;
}
if(preg_match("/^[\w\-'\s]/", $_POST['subject'])){
$subject = $_POST['subject'];
}
else{
$errsub = "<strong>Please enter a subject.</strong>";
$hasErrors = true;
}
if (!empty($_POST['recipient'])) {
for ($i=0; $i < count($_POST['recipient']);$i++) {
$recipient = $_POST['recipient'];
}
}else{
$errrec = "<strong>Please select a recipient</strong>";
$hasErrors = true;
}
$message = $_POST['message'];
}
if ($hasErrors){
echo "<strong>Error! Please fix the errors as stated.</strong>";
}else{
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject. "&recipient=".$recipient. "&message=".$message);
exit();
}
?>
form.php
<?php
$name = $_GET['name'];
$email = $_GET['email'];
$subject = $_GET['subject'];
$recipient = $_GET['recipient'];
$message = $_GET['message'];
echo "<h2>Thank You</h2>";
echo "<p>Thank you for your submission. Here is a copy of the details that you have sent.</p>";
echo "<strong>Your Name:</strong> ".$name. "<br />";
echo "<strong>Your Email:</strong> ".$email. "<br />";
echo "<strong>Subject:</strong> ".$subject. "<br />";
echo "<strong>Recipient:</strong>" .$recipient. "<br />";
echo "<strong>Message:</strong> <br /> " .$message;
?>
If you would like to transfer the data from contact.php to form.php you should use something like this:
contact.php
$data = urlencode(
serialize(
array(
"name" => $name,
"email" => $email,
"subject" => $subject,
"message" => $message)
));
header('Location: form.php?data=' . $data);
form.php
$data = unserialize(urldecode($_GET['data']));
$name = $data["name"];
$email = $data["email"];
$subject = $data["subject"];
$message = $data["message"];
This serializes the array of data from contact.php then URL encodes it and sends it as a GET variable to form.php. After, form.php URL decodes and unserializes the data for use.
The problem is when you header("Location:") to form.php, all the POST values are lost. You have to either resend them with the header, or modify them into GET and retrieve them again. It should be more efficient to have them both (contact.php AND form.php) in one page. That way, the form data only has to be sent once.
You could probably just send the POST values as GET over to form.php like this.
contact.php:
header("Location: form.php?name=".$name."&email=".$email."&subject=".$subject."&message=".$message);
form.php (to retrieve the values):
$name = $_GET['name'];
$email = $_GET['email'];
$message = $_GET['message'];
$subject = $_GET['subject'];
If you want to display form elements then you have to use this approach.
<form method="POST" action="contact.php">
Email<input type="text" name="email">
.......
.......
.......
// All elements
</form>
This may help you.
Give action in your form in contact.php
<form action="form.php">

PHP Feedback form Checkbox error

Ok here is a shortened version of the php for my contact form, (the checkboxes are not being sent through correctly)
<?php
//please fill this in at least!
$myemail = "";
$title = "Feedback Form";
if(isset($_POST['submit'])) { //form has been submitted
//set variables with filters
$cont_name = filter_var($_POST['cont_name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['cont_email'], FILTER_SANITIZE_STRING);
$phone = filter_var($_POST['cont_phone'], FILTER_SANITIZE_STRING);
$first_time = filter_var($_POST['first_time'], FILTER_SANITIZE_STRING);
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
function valid_email($str){
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;}
$errors = 0; //by default there are no errors
$trimcont_name = trim($cont_name);
if(empty($trimcont_name)){
//the name field is empty
$errors = 1; //tips off the error messages below
$errorcont_name = "The name field is empty"; //this error is displayed next to the label
}
if(!valid_email($email)) {
//email is invalid or empty
$errors = 1;
$erroremail = "The email address was not valid";
}
$trimphone = trim($phone);
if(empty($trimphone)){
//the phone field is empty
$errors = 1;
$errorphone = "The phone field is empty";
}
$trimfirst_time = trim($first_time);
if(empty($trimfirst_time)){
//the first_time field is empty
$errors = 1;
$errorfirst_time = "This field is empty";
}
$trimhear_about = trim($hear_about);
if(empty($trimhear_about)){
//the hear_about field is empty
$errors = 1;
$errorhear_about = "This field is empty";
}
if($spam != "") {
//spam was filled in
$errors = 1;
$errorspam = "The Spam box was filled in";
}
if($errors == 0) {
$sendto = $myemail;
$message = <<<DATA
DETAILS
Name: $cont_name
Email: $email
Phone: $phone
Was this the first time you have been to us?
$first_time
How did you hear about us?
$hear_about
DATA;
$headers = 'From: ' . $name . '<' . $email . '>';
if(mail($sendto, $title, $message, $headers)) {
//this is where it sends, using the php mail function
$success = true;
//set all the variables to blank to prevent re-submitting.
$cont_name = "";
$email = "";
$phone = "";
$hear_about = "";
$first_time = "";
} else {
$success = false;
}
} else {
$success = false;
}
}
?>
And the area not functioning correctly is
<fieldset>
<legend>How did you hear about us? <span class="phpformerror"><?php echo $errorhear_about; ?></span></legend>
<div><input type="checkbox" name="hear_about[]" value="Web" /> Web</div>
<div><input type="checkbox" name="hear_about[]" value="Newspaper" /> Newspaper</div>
<div><input type="checkbox" name="hear_about[]" value="Radio" /> Radio</div>
<div><input type="checkbox" name="hear_about[]" value="Driving" /> Driving Past</div>
<div><input type="checkbox" name="hear_about[]" value="Referal" /> Referal</div>
<div><input type="checkbox" name="hear_about[]" value="Other" /> Other</div>
</fieldset>
At the moment it will only come through displaying one of the variables if multiple variables are selected.
hear_about is an array and filter_var() does not handle arrays correctly. Instead use filter_var_array():
$hear_about = filter_var_array($_POST['hear_about'], FILTER_SANITIZE_STRING);
Remember that $hear_about is an array, and must be treated like one throughout your code (e.g. just using $hear_about won't work, it needs to be $hear_about[0], $hear_about[1], etc).
So for example in your trim line you would need something like:
foreach($hear_about as $key => $value) {
$trimhear_about[$key] = trim($value);
if(empty($trimhear_about[$key])){
//the hear_about field is empty
$errors = 1;
$errorhear_about[$key] = "This field is empty";
}
}
This will preserve the benefits of dealing with an array.
$_POST['hear_about'] is an array of values. You are handling it as a simple string!
I think you can solve simply replacing the line:
$hear_about = filter_var($_POST['hear_about'], FILTER_SANITIZE_STRING);
With:
$hear_about = filter_var(implode(', ', $_POST['hear_about']), FILTER_SANITIZE_STRING);
The implode function (doc) "transform" an array to a string by concatenating the array values with the given glue. So you can just concatenate selected "How did you hear about us?" options with a comma and then use the resulting string as the other data.

Categories