Email validation using PHP - php

I have a form for which i am trying to validate the email address. If the email address is incorrect i want a value of "Please type a valid email address." to be returned into the "email" input box on the form. What am i doing wrong? No validation is taking place. I receive the form information at my email and once submitted the user is sent to the "Thank you" page, but no validation. I can put anything in the "email" input and the form will submit.
<form action="../php/contact.php" method="post">
<p>First Name:</p>
<input class="box_style" type="text" name="first_name" required maxlength="20" />
<p>Last Name:</p>
<input class="box_style" type="text" name="last_name" required maxlength="25" />
<p>Email:</p>
<input class="box_style" type="text" name="email" required maxlength="50" />
<p>Contact Number (optional):</p>
<input class="box_style" type="text" name="contact_number" maxlength="12" />
<p>How did you find us?</p>
<select class="box_style" name="how" required>
<option value="choose">Select...</option>
<option value="referal">Referal</option>
<option value="website">Website</option>
<option value="search">Search Engine</option>
<option value="card">Business Card</option>
</select>
<p>Enquiries:</p>
<textarea class="box_style" name="inquiries" cols="30" rows="10"></textarea>
<input class="box_style" type="submit" name="submit" value="Submit"/>
</form>
and this is the php
<?php
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$fName = $lName = $email = $cNum = $how = $enquiries = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fName = test_input($_POST["first_name"]);
$lName = test_input($_POST["last_name"]);
$cNum = test_input($_POST["contact_number"]);
$how = test_input($_POST["how"]);
$enquiries = test_input($_POST["enquiries"]);
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
}};
$email_from = 'my#email.com';
$email_subject = "New Inquiry";
$email_body = "You have received a new message from" ." ". "$fName" ." ". "$lName" ."\n".
"$inquiries"."\n".
"Referal Type:" ." ". "$how" ."\n".
"Contact Number:" ." ". "$cNum" ."\n";
$to = "my#email.com";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
mail($to,$email_subject,$email_body,$headers);
?>
Thank You

Here's a simplified version of the OP's code that demonstrates how to display the error message by having the action attribute of the form be the same url as that which displays the form. The code also exemplifies some nice touches for the user:
<?php
include("php4myform.php");
?>
<html>
<head>
<title>Email Validate</title>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<label for="email">Email: </label>
<input id="email" name="email" required maxlength="50" value="<?php echo $e_mess; ?>">
<input type="submit" name="submit" value="Submit">
<input type="reset" id="clear" value="clear">
</form>
<script src="myJS4forms.js"></script>
</body>
</html>
php4myform.php:
<?php
$e_mess = "";
if ( isset($_POST['submit']) && $_POST != null) {
$tainted_email = trim($_POST["email"]);
$sanitized_email = filter_var($tainted_email, FILTER_SANITIZE_EMAIL);
if( !filter_var( $sanitized_email, FILTER_VALIDATE_EMAIL ) ) {
$e_mess = "Please type a valid email address.";
}
else
{
// Data is good to go.
}
}
myJS4forms.js:
var d = document;
d.g = d.getElementById;
var email = d.g("email");
var reset = d.g("clear");
function selFoc(obj){
obj.focus();
obj.select();
}
window.onload = function() {
selFoc( email );
};
reset.addEventListener("click",function(e) {
e.preventDefault();
email.value=null;
selFoc( email );
});
A few notes:
The drawback of testing with $_SERVER["REQUEST_METHOD"] is that the user might submit an empty form. Therefore, the PHP code in this example tests to see if the form was submitted and if the POST contains any data.
It is ill-advised to use htmlspecialchars() with filter_var and the parameter FILTER_EMAIL_SANITIZE; see this discussion and here, too. The code employs htmlspecialchars() instead to safeguard $_SERVER['PHP_SELF'] -- basis: this article.
I removed stripslashes() since magic quotes are deprecated and gone as of PHP5.4; see the online Manual. (Using addslashes() to escape data is inadvisable -- better to use mysqli_real_escape_string().) Also, filter_var with FILTER_SANITIZE_EMAIL will remove any slashes (see Manual).

If you redirect the user using a "header()" function, you need to stop the execution of the script. So the correct way would be something like this:
$email = test_input($_POST["email"]);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
print "<p>Please type a valid email address.</p>";
header("Location: www.mysite/thankyou.com");
exit();
}
If you don't terminate the script, it will continue executing the rest of the file.
Secondly, if you print something to the user and immediately redirect him elsewhere, he will never see the message. If you want to do a redirection and show the message there, you need to store the message first, probably in a session variable, and then show it on the "landing page".

Related

PHP email script not sending all form fields

IF (I Started Receiving Spam Bot Forms)
THEN (I Implemented New PHP Email script using a basic Honey Pot Method)
$ERROR (New PHP is not sending ALL the forms fields. Upon sending the form, my email is only receiving the, textarea id="message", field)
$LOG_FILE (My previous PHP script implemented a dynamic catch-all solution for form fields)
$FAILED_SOLUTION (Conversely I attempted to add the individual, $phone & $address fields manually on lines #6 7 & 14 of the PHP but am still only receiving the, textarea id="message", field)
$NOTES (I am self taught & typically only deal with PHP on a need to know basis. Please try to keep it simple and include a step-by-step explanation. Feel free to suggest any "best practices" i may have overlooked unrelated to my problem!)
$QUESTION = "Can someone show me how to call the other form fields in the PHP script to send to my email?"
$SUCCESS = "Thanks in Advance For Any Help That Maybe Given!";
PHP:
<?php
if($_POST){
$to = 'your-email-here#gmail.com';
$subject = 'Contact Form Submission';
$name = $_POST['name'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$email = $_POST['email'];
$message = $_POST['message'];
$robotest = $_POST['robotest'];
if($robotest)
$error = "Spam Protection Enabled";
else{
if($name && $phone && $address && $email && $message){
$header = "From: $name <$email>";
if(mail($to, $subject, $message,$header))
$success = "Your message was sent!";
else
$error = "Error_36 there was a problem sending the e-mail.";
}else
$error = "Error_09 All fields are required.";
}
if($error)
echo '<div class="msg error">'.$error.'</div>';
elseif($success)
echo '<div class="msg success">'.$success.'</div>';
}
?>
HTML FORM:
<form method="post" action="Form_Email.php">
<input type="text" id="name" name="name" placeholder="name" required>
<input type="text" id="phone" name="phone" placeholder="phone" required>
<input type="text" id="address" name="address" placeholder="address" required>
<input type="text" id="email" name="email" placeholder="email" required>
<textarea id="message" name="message" placeholder="message" required> </textarea>
<p class="robotic">
<input name="robotest" type="text" id="robotest" class="robotest" autocomplete="off"/>
</p>
<input type="submit" id="SEND" value="Submit">
</form>
Your message contains only $_POST['message'] for now. If you want to append other values, use concatenation on your $message variable.
$message .= ($name . $phone . $address . $etc)
Notice: A $foo .= $bar construction stands for $foo = $foo . $bar.
Do not forget about whitesigns such as spaces or new lines wherever you want. Simply concatenate ' ' or "\n".
After that, just send a mail using your $message as message.

Contact Form Disappearing When Div is Set?

Ok, so I've got a contact form:
<?php
if (isset($_POST['subtest'])) {
$to = 'thomofawsome#gmail.com';
$name = $_POST['firstname'];
$lastName = $_POST['lastname'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$comments = $_POST['comments'];
$Message = <<< STOP
From: $name $lastName
Email: $email
In: $city, $state, $zip
Comments: $comments
STOP;
$subject = "Contact Request";
$headers = 'From: system';
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
exit();
}
else {
echo 'Mail Failed';
}
}
?>
<form name="contact_form" action="" method="post">
<input type="hidden" name="subtest" value="true">
First Name:<br>
<input type="text" name="firstname">
<br>
Last Name:<br>
<input type="text" name="lastname">
<br>
Email Address:<br>
<input type="text" name="email">
<br>
City:<br>
<input type="text" name="city">
<br>
State:<br>
<input type="text" name="state">
<br>
Zip:<br>
<input type="text" name="zip">
<br>
Comments:<br>
<textarea name="comments"></textarea>
<br>
<input id="submit" type="submit" name="submit" value="Send">
<br>
</form>
The problem is I want the echo mail sent correctly formatted (with a green color, positioned correctly on the page, etc.). As you can see, I've put it in a div. When I submit the form though, I'm redirected back to the form page, except the entire form and footer disappear, and Mail sent appears on the bottom of the page (correctly formatted).
Any ideas?
The exit() function prevents the rest of the script from executing, which includes your form and footer. Remove it and it will work.
if (mail($to, $subject, $Message, $headers)) {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
As Raidenance pointed out, if someone refreshes this page after posting the form it will resend the email address. A better solution to this problem is to post your contact form to another url (/contact/submit for instance) and on completion of the script execution at that url simply redirect back to the contact form with a parameter
header("Location:/contact?success=true");
Then on your contact form page:
if (isset($_GET['success']) && $_GET['success'] == "true") {
echo '<div id="thanks">Mail sent</div>';
} else {
echo 'Mail Failed';
}
This will prevent the issue of the user reloading and receiving the email multiple times.

PHP: Wait for User Input Before Executing Script

I have an html input form as well as a php email script that takes these values on the same page.
The problem is that before I submit any data into the forms I get a blank email because my php script is not waiting for the user input.
I don'y wan't to use another page for my email script because I don't want to pass variables through GET and I don't know how to implement sessions yet.
Thanks and here is my code
<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>
<?php
if (!isset($_POST['submit'])) {
echo 'you have hit the submit button';
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'trustyclient#yoursite.com';
$email_subject = "Message from client";
$email_body = "Message from: $visitor_email \n \n Message:$message";
$to = "myemail#myemail.com";
$headers = "from:adam\r\n";
mail($to,$email_subject,$email_body,$headers);
} else {
echo 'You have not hit the submit button yet';
}
?>
First, give your submit button a name, like 'submit' (because you've already referenced that name in the PHP). Example:
<input type="submit" name="submit" value="Send Email">
Now you can actually use $_POST['submit'] in your code.
Then another tweak:
When you state if (!isset($_POST['submit'])) {, the following code runs if the submit button has not been pressed, because of the !. To fix, just remove the !, making it:
if (isset($_POST['submit'])) {
! tells the if statement to evaluate to true if the following expression, here isset($_POST['submit']), evaluates to false. Therefore ! means "if the opposite".
NB: Also, the concept that the PHP runs when the submit button is pressed is slightly off. The submit button triggers that page to load a different page (or the same page). The PHP code runs only once when the page loads.
Try this.
<div id = "center">
<form action="post.php" name="emailform" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="message">
<input type="submit" value="Send Email">
</form>
</div>
<?php
if (isset($_POST['submit'])) {
echo 'you have hit the submit button';
if (empty(trim($_POST['name'])) || empty(trim($_POST['email'])) || empty(trim($_POST['message']))) {
echo 'Some fields are empty.';
} else {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];
$email_from = 'trustyclient#yoursite.com';
$email_subject = "Message from client";
$email_body = "Message from: $visitor_email \n \n Message:$message";
$to = "myemail#myemail.com";
$headers = "from:adam\r\n";
mail($to,$email_subject,$email_body,$headers);
}
} else {
echo 'You have not hit the submit button yet';
}
?>

My PHP form submits but does not validate the email address

I am an eager novice with PHP so please forgive my errors as I am learning as I go. Basically, I am building a simple contact form for my website and have successfully been able to have the form send the user's first and last name, subject, email address and message. I am using a second file, "form_process.php" to process the form data from "index.php".
The problem is that the email address does not seem to be validating and will send any words typed. I would greatly appreciate it if some more seasoned eyes could take a look and help me sort this out. Thank you in advance.
Michael.
HTML:
<div id="form">
<form action="form_process.php" method="post" enctype="multipart/form-data">
<p>
<input type="text" maxlength="100" size="50" name="fName" value="<?php echo $stored_fName;?>" placeholder="First Name" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="lName" value="<?php echo $stored_lName;?>" placeholder="Last Name" />
</p>
<p>
<input type="text" maxlength="80" size="50" name="email" value="<?php echo $stored_email;?>" placeholder="Email Address" />
</p>
<p>
<input type="text" maxlength="100" size="50" name="subject" value="<?php echo $stored_subject;?>" placeholder="Subject" />
</p>
<p>
<textarea name="message" rows="6" cols="38" placeholder="Message"></textarea>
</p>
<br />
<input type="submit" value="Submit" name="submit" />
<input type="reset" value="Clear" name="clear">
</form>
</div>
<!-- form ends -->
PHP: "form_process.php"
<?php
session_start();
// Report all PHP errors
error_reporting(E_ALL);
//use $_POST to to store data from submitted form into these variables
$fName = check_input($_POST['fName']);
$lName = check_input($_POST['lName']);
$sender = check_input($_POST['email']);
$subject = check_input($_POST['subject']);
$message = check_input($_POST['message']);
//check_input function to strip unnessessary characters and sanitize user data
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$name = $fName ." ". $lName;//concatenating first and last names to new name variable
$sanitizedEmail = filter_var($sender, FILTER_SANITIZE_EMAIL);
//generates error messages on index.php if form fields left blank
if ($fName == ''){
header("Location:index.php?message=1");
exit();
}
if ($lName == ''){
header("Location:index.php?message=2");
exit();
}
if ($sender == ''){
header("Location:index.php?message=3");
exit();
}
if ($subject == ''){
header("Location:index.php?message=4");
exit();
}
if ($message == ''){
header("Location:index.php?message=5");
exit();
}
//headers
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= $name . "\r\n";
$headers .= "From:" . " " . $sanitizedEmail . "\r\n";
//mail function
$to = "me#myemail.com";
$subject = $subject;
$message = $message;
//send message
$send_message = mail($to,$subject,$message,$headers);
if($send_message){
header("Location:index.php?message=6");
}else {
header("Location:index.php?message=9");
exit();
}
?>
"index.php" error messages:
<?php
//all fields empty until user inputs data for session to store
$stored_fName = '';//init as NULL
$stored_lName = '';//init as NULL
$stored_email = '';//init as NULL
$stored_subject = '';//init as NULL
$stored_message = '';//init as NULL
//session data used to repopulate form fields if any info is missing or incorrect
if (isset($_SESSION['fName'])){
$stored_fName = $_SESSION['fName'];
}
if (isset($_SESSION['lName'])){
$stored_lName = $_SESSION['lName'];
}
if (isset($_SESSION['email'])){
$stored_email = $_SESSION['email'];
}
if (isset($_SESSION['subject'])){
$stored_subject = $_SESSION['subject'];
}
if (isset($_SESSION['message'])){
$stored_message = $_SESSION['message'];
}
//error messages displayed to user if text fields have been left blank
$_GET['message'];
if ($_GET['message'] == 1) {//first name
echo "<strong>Please type your first name.</strong>";
}
if ($_GET['message'] == 2) {//last name
echo "<strong>Please type your last name.</strong>";
}
if ($_GET['message'] == 3){//email address
echo "<strong>Please type an email address.</strong>";
}
if ($_GET['message'] == 4){//subject
echo "<strong>Please type a subject.</strong>";
}
if ($_GET['message'] == 5){//message text
echo "<strong>Please type your message.</strong>";
}
if ($_GET['message'] == 6){//message success from form_process.php
echo "<strong>Your message was sent successfully. Thank you.</strong>";
}
if ($_GET['message'] == 9){
echo "<strong>I'm sorry but your message was not sent. Please try again, thank you.</strong>";
}
?>
You should be using it like this:
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
// is email
$sender = $email;
}else{
// isn't email
$sender = '';
}
Read more about PHP Validate Filters

My PHP contact form is shooting blanks

Please forgive the tongue-in-cheek title, but I've been trying for the last hour to get my contact form to work properly. It sends the email just fine but it leaves out all the relevant data (name, email, etc.)
I've modified a PHP contact form tutorial, but I don't know where I've gone wrong.
The HTML:
<form name="form1" method="post" action="send_contact.php">
<fieldset>
<h3>Name</h3>
<input name="name" type="text" id="name">
<h3>Email (required)</h3>
<input name="email" type="text" id="email">
<h3>Phone (required)</h3>
<input name="telephone" type="text" id="telephone">
<h3>Desired appointment time/date</h3>
<input name="time" type="text" id="time">
<input type="submit" name="Submit" value="Submit">
</fieldset>
</form>
The PHP:
<?php
// customer name
$customer_name = "$name";
// customer email
$mail_from = "$email";
// customer telephone
$customer_telephone = "$telephone";
// desired appointment time
$appointment_time = "$time";
// subject
$subject = "Appointment for $customer_name";
// message
$message = "$customer_name would like to book an appointment for $appointment_time";
// header
$header = "from: $customer_name <$mail_from>";
// recipient
$to = 'my#emailaddress.com';
$send_contact = mail($to,$subject,$message,$header);
if($send_contact){
echo "We've recived your contact information";
}
else {
echo "ERROR";
}
?>
You don't need quotes.
$customer_name = "$name";
$customer_name = $name;
You should really use post to grab the data.
$customer_name = $_POST['name'];
you need to be looking in the super global $_POST for your variables. for example
$customer_name = $_POST['name'];
if your posting the data you need to get it from the post: I would trim it also
$customer_name = trim( $_POST['name'] );

Categories