How can I merge these 2 PHP scripts? - php

I have a jQuery AJAX form and I'd like for it to do better validation on input - on the PHP side. Here is the PHP script that works with AJAX:
while (true) {
if (empty($_POST['name'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter your name.';
break;
}
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter your email.';
break;
}
if (empty($_POST['message'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter your message.';
break;
}
break;
}
if (!$return['error'])
$return['msg'] = "Thank you: {$_POST['name']}<br />email address: {$_POST['email']}<br />Your Message: {$_POST['message']}";
echo json_encode($return);
And here is the PHP script I use elsewhere for validation:
<?php
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}
}
?>
Please can someone who know their PHP help me - I dont have a clue how to put this together.

try like this. i think this code alone working good for what you want.
$subject = "Website Contact Form Enquiry";
//If the form is submitted
if(isset($_POST['submit'])) {
//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
$hasError = true;
$return['msg'] = 'You did not enter your name.';
} else {
$name = trim($_POST['contactname']);
}
//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '') {
$hasError = true;
$return['msg'] = 'You did not enter your email.';
} else if (!eregi("^[A-Z0-9._%-]+#[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
$hasError = true;
$return['msg'] = 'You did not enter valid email.';
} else {
$email = trim($_POST['email']);
}
//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
$hasError = true;
$return['msg'] = 'You did not enter your message.';
} else {
if(function_exists('stripslashes')) {
$comments = stripslashes(trim($_POST['message']));
} else {
$comments = trim($_POST['message']);
}
}
//If there is no error, send the email
if(!isset($hasError)) {
$emailTo = 'info#bgv.co.za'; //Put your own email address here
$body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
$headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
mail($emailTo, $subject, $body, $headers);
$emailSent = true;
}else{
echo json_encode($return);
}
}

Related

PHP Form validation using 'if'

I'm currently building a very small 'contact' form for use on a personal site.
The form works, and each validation 'if' statement works individually, however, if for example I input a valid email address and phone number but leave the message blank, the email still sends and I get the success message.
My guess would be to include the small 'if' statements into the one checking whether my required fields are not empty, though i'm not sure how to do this correctly as it is nesting multiple 'if's into one.
Cheers
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
?>
<!-- Display red error box or green success box depending on which is true -->
<?php if(!empty($errors)): ?>
<div class="validationbox | errorsbox">
<?php echo $errors; ?>
</div>
<?php elseif(empty($errors)): ?>
<div class="validationbox | successbox">
<?php echo $success; ?>
</div>
<?php
$message = ''; // Blank message to start with so we can append to it.
// Construct the message
$message .= "
Name: {$_POST['thename']};
Email: {$_POST['email']};
Number: {$_POST['number']};
Enquiry-type: {$_POST['enquiry-options']};
Message: {$_POST['comments']};
";
// test#testdomain.com
$to = 'test-email-deleted-for-stackoverflow';
$subject = 'Message from Portfolio';
$from = $_POST['thename'];
// YourSite#domain.com
$fromEmail = 'test-email-deleted-for-stackoverflow';
$header = 'From: ' . $from . '<' . $fromEmail . '>';
mail($to,$subject,$message,$header);
?>
<?php endif; ?>
<?php endif; ?>
Your problem is that you are resetting $errors back to '' each time one of your validation conditions passes:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
$errors = '';
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
You shouldn't do that, just leave error messages to whatever it previously was. This way, when you get to the end, $errors will contain a string of all the error messages combined. Since there could be multiple messages, you may want to put a break a the end of each one:
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.<br>";
}
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address<br>";
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number<br>";
}
In the case of email, you may want to only display the 'invalid email address' only when something was actually filled in, so you could also check to ensure there is something in there, before you determine if the format is valid or not:
if (!empty($email) && !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
Based on the information Supplied, i think you should use a complex if-elseif-else statement like so:
`if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
} `
in your particular case:
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} elseif(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors = 'Error:invalid email';
}elseif(!preg_match("/^\(?0( *\d\)?){9,10}$/", $number){
$errors .= "Error: Invalid phone number";
} else {
//Do this on successful validation comes here
}
try below code it helps you.
<?php
// Validation goes here
$errors = '';
$success = 'Success! Your message has been sent. You should receive a reply within 48 hours.';
$email = $_POST['email'];
$name = $_POST['thename'];
$comments = $_POST['comments'];
$number = $_POST['number'];
if(empty($name) || empty($email) || empty($comments)) {
$errors .= "Error: please input a name, email address and your message.";
} else {
if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email)) {
$errors .= "Error: Invalid email address";
} else {
$errors = '';
}
if (!preg_match("/^\(?0( *\d\)?){9,10}$/", $number)) {
$errors .= "Error: Invalid phone number";
} else {
$errors = '';
}
}
?>

Trying to send an email in PHP only after the submit button is pressed and the form is valid

I am new to PHP and currently getting back to HTML. I have made a form and have the data sent and validated by PHP but I am trying to send the email to myself only after the data had been validated and is correct. Currently if the page is loaded I think it send an email and it will send whenever I hit submit without the data being correct.
Here is where I validate the data:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
function validate_info($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Sorry its a little lengthy.
Here is where I try to send the email. I have tried two different attempts and both have the same result.
<?php
if (!empty($fnameErr) || !empty($lnameErr) || !empty($subjectErr) || !empty($emailErr) || !empty($commentErr) || !empty($websiteErr) || !empty($findoptionErr))
{
echo "Sent!!";
}else
{
echo"Not Sent!!";
}
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
?>
Once again sorry for the length. Thanks in advance also sorry if this is a double question or not described enough I am also new to stack overflow.
Please try:
<?php
//Set main variables for the data.
$fname = $lname = $email = $subject = $website = $likedsite = $findoption = $comments = "";
//Set the empty error variables.
$fnameErr = $lnameErr = $emailErr = $subjectErr = $commentsErr = $websiteErr = $findoptionErr = "";
//Initialize variable used to identify form is valid OR not.
$formValid = true;
//Check to see if the form was submitted.
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//Check the 'First Name' field.
if (empty($_POST["fname"]))
{
$formValid = false;//Form not validate
$fnameErr = "First Name is Required.";
}
else
{
$fname = validate_info($_POST["fname"]);
}
//Check the 'Last Name' field.
if (empty($_POST["lname"]))
{
$formValid = false;//Form not validate
$lnameErr = "Last Name is Required.";
}
else
{
$lname = validate_info($_POST["lname"]);
}
//Check the 'E-Mail' field.
if (empty($_POST["email"]))
{
$formValid = false;//Form not validate
$emailErr = "E-Mail is Required.";
}
else
{
$email = validate_info($_POST["email"]);
//Check if valid email.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
{
$formValid = false;//Form not validate
$emailErr = "Invalid E-Mail Format.";
}
}
//Check the 'Subject' field.
if (empty($_POST["subject"]))
{
$formValid = false;//Form not validate
$subjectErr = "Subject is Required.";
}
else
{
$subject = validate_info($_POST["subject"]);
}
//Check the 'Website' field.
if (empty($_POST["siteurl"]))
{
$website = "";
}
else
{
$website = validate_info($_POST["siteurl"]);
//Check if valid URL.
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website))
{
$formValid = false;//Form not validate
$websiteErr = "Invalid URL.";
}
}
//Check the 'How Did You Find Us' options.
if (empty($_POST["howfind"]))
{
$formValid = false;//Form not validate
$findoptionErr = "Please Pick One.";
}
else
{
$findoption = validate_info($_POST["howfind"]);
}
//Check the comment box.
if (empty($_POST["questioncomments"]))
{
$formValid = false;//Form not validate
$commentsErr = "Questions/Comments are Required.";
}
else
{
$comments = validate_info($_POST["questioncomments"]);
}
//Pass any un-required data.
$likedsite = validate_info($_POST["likedsite"]);
}
//If every variable value set, send mail OR display error...
if (!$formValid){
echo"Form not validate...";
}
else {
//Make the message.
$message =
"
First Name: $fname.\n
Last Name: $lname.\n
Website: $website\n
Did They Like the Site? $likedsite.\n
How They Found Us. $findoption.\n
Question/Comments:\n
$comments.
";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
if($sendMail){
echo "Mail Sent!!";
}
else {
echo "Mail Not Sent!!";
}
}
function validate_info($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I edit my answer as per some change. Now this code only allow send mail if form required fields are not empty and all fields value are valid as per your validation.
Let me know if there is any concern.!
from what i was able to conceive, u are
trying to apply 'OR' in if condition- should be changed to AND i.e. change || to &&
you are checking for not empty error variables... which should be changed to verify if they all are empty or not.
if (empty($fnameErr) && empty($lnameErr) && empty($subjectErr) && empty($emailErr) && empty($commentErr) && empty($websiteErr) && empty($findoptionErr))
{
echo "sent";
}
Instead of writing lengthy conditions.
Assign all error messages to a single variable and append errors to it ($errorMsg). You can avoid lengthy if else ladder by doing this.
Change empty($_POST["email"]) to !isset($_POST["email"]) - In all statements.
Then update the condition to following,
<?php
if($errorMsg == ''){
//Make the message.
$message ="
First Name: ".$fname.".\n
Last Name: ".$lname."\n
Website: ".$website."\n
Did They Like the Site? ".$likedsite."\n
How They Found Us. ".$findoption."\n
Question/Comments:\n
".$comments." ";
$message = wordwrap($message, 70);
$headers = "From: $email";
mail("me#gmail.com", $subject, $message, $headers);
}else{
// Show $errorMsg
}
?>
Make it simple, I hope this helps.

It wont send the message (EMAIL)PHP [duplicate]

This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 8 years ago.
i dont know why it wont send it just echo's this msg Oops.. There seems to be a technical errorWe are truly sorry, please check again later
i dont know whats the problem maybe i'm overlooking,
can u pls tell me i have i gone wrong.
if you need the html code let me know
suggestions on how to improve this code would be gratefully appreciated :)
PHP CODE:
<?php
function clean($str)
{
$str = mysql_real_escape_string($str);
$str = htmlspecialchars($str);
$str = strip_tags($str);
return($str);
}
if(isset($_POST['name']) &&
isset($_POST['address']) &&
isset($_POST['hp']) &&
isset($_POST['email']) &&
isset($_POST['rm']) &&
isset($_POST['service']) &&
isset($_POST['name-owner']) &&
isset($_POST['name-rep']) &&
isset($_POST['contract-from']) &&
isset($_POST['contract-to']) &&
isset($_POST['agree']) &&
isset($_POST['submit'])){
$name = clean($_POST['name']);
if($name == NULL || $name == "")
{
die ("Please enter your name");
$errormsg = "<button class=\"\" onClick=\"history.go(-1)\"> Retry</button> ";
}
$address = clean($_POST['address']);
if($address == NULL)
{
die ("Please enter your Business address");
$errormsg;
}
$hp = clean($_POST['hp']);
if($hp == NULL)
{
die ("Please enter your Phone No.");
}
$email = clean($_POST['email']);
if($email == NULL)
{
die ("Please enter your Email address");
$errormsg;
}
$url = clean($_POST['url']);
$rm = clean($_POST['rm']);
if($rm == NULL)
{
die ("Please enter your Amount/Percentage");
$errormsg;
}
$service = clean($_POST['service']);
if($service == NULL)
{
die ("Please enter your Service/Item offer");
$errormsg;
}
$nameowner = clean($_POST['name-owner']);
if($nameowner == NULL)
{
die ("Please enter the Name of Owner/Manager");
$errormsg;
}
$namerep = clean($_POST['name-rep']);
if($namerep == NULL)
{
die ("Please enter the Name of Representative");
$errormsg;
}
$contract_from = clean($_POST['contract-from']);
if($contract_from == NULL)
{
die ("Please enter the Contract date");
$errormsg;
}
$contract_to = clean($_POST['contract-to']);
if($contract_to == NULL)
{
die ("Please enter the Contract date");
$errormsg;
}
$agree = clean($_POST['agree']);
$message = "Business Name: ".$name."\r\n";
$message = "Business Address: " .$address. "\r\n";
$message = "Phone No.: ".$hp."\r\n";
$message = "Email: ".$email."\r\n";
$message = "URL: <a href=\"".$url."\"\r\n ";
$message = "Amount/Percentage offer: ".$rm."\r\n";
$message = "Items/Service offer:".$service."\r\n";
$message = "Name of Owner/Manager".$nameowner."\r\n";
$message = "Name of Representative".$namerep."\r\n";
$message = "This contract is valid for one(1) year from: <b>".$contract_from."</b> to <b>".$contract_to."</b> \r\n";
$message = $agree."\r\n";
$to = 'contact#example.com';
$subject = 'Contact query';
$headers = 'From:' . "$email \r\n" .
'Reply-To:' . "$email \r\n" .
'X-Mailer: PHP/' . phpversion();
$send = mail($to, $subject, $message, $headers);
if ($send == TRUE)
{
echo "<p>Message has been sent</p>";
echo "<p>Thank you</p>";
}
else
{
die ("<p>Message failed to send</p>");
}
}else {
echo "<p>Oops.. There seems to be a technical error<br>We are truly sorry, please check again later</p>";
}
?>
Probably one of the POST Variable is not set and thus it might throw you to the else part to show the error
You must attach the require_once "Mail.php"; require_once('Mail/mime.php'); into your code so that the function works for you
<?php
function clean($str)
{
$str = mysql_real_escape_string($str);
$str = htmlspecialchars($str);
$str = strip_tags($str);
return($str);
}
if(isset($_POST['submit']))
{
$name = clean($_POST['name']);
if($name == NULL || $name == "")
{
die ("Please enter your name");
$errormsg = "<button class=\"\" onClick=\"history.go(-1)\"> Retry</button> ";
}
$address = clean($_POST['address']);
if($address == NULL)
{
die ("Please enter your Business address");
$errormsg;
}
$hp = clean($_POST['hp']);
if($hp == NULL)
{
die ("Please enter your Phone No.");
}
$email = clean($_POST['email']);
if($email == NULL)
{
die ("Please enter your Email address");
$errormsg;
}
$url = clean($_POST['url']);
$rm = clean($_POST['rm']);
if($rm == NULL)
{
die ("Please enter your Amount/Percentage");
$errormsg;
}
$service = clean($_POST['service']);
if($service == NULL)
{
die ("Please enter your Service/Item offer");
$errormsg;
}
$nameowner = clean($_POST['name-owner']);
if($nameowner == NULL)
{
die ("Please enter the Name of Owner/Manager");
$errormsg;
}
$namerep = clean($_POST['name-rep']);
if($namerep == NULL)
{
die ("Please enter the Name of Representative");
$errormsg;
}
$contract_from = clean($_POST['contract-from']);
if($contract_from == NULL)
{
die ("Please enter the Contract date");
$errormsg;
}
$contract_to = clean($_POST['contract-to']);
if($contract_to == NULL)
{
die ("Please enter the Contract date");
$errormsg;
}
$agree = clean($_POST['agree']);
$message = "Business Name: ".$name."\r\n";
$message = "Business Address: " .$address. "\r\n";
$message = "Phone No.: ".$hp."\r\n";
$message = "Email: ".$email."\r\n";
$message = "URL: <a href=\"".$url."\"\r\n ";
$message = "Amount/Percentage offer: ".$rm."\r\n";
$message = "Items/Service offer:".$service."\r\n";
$message = "Name of Owner/Manager".$nameowner."\r\n";
$message = "Name of Representative".$namerep."\r\n";
$message = "This contract is valid for one(1) year from: <b>".$contract_from."</b> to <b>".$contract_to."</b> \r\n";
$message = $agree."\r\n";
$to = 'contact#example.com';
$subject = 'Contact query';
$headers = 'From:' . "$email \r\n" .
'Reply-To:' . "$email \r\n" .
'X-Mailer: PHP/' . phpversion();
$send = mail($to, $subject, $message, $headers);
if ($send == TRUE)
{
echo "<p>Message has been sent</p>";
echo "<p>Thank you</p>";
}
else
{
die ("<p>Message failed to send</p>");
}
}
else
{
echo "<p>Oops.. There seems to be a technical error<br>We are truly sorry, please check again later</p>";
}
?>

Form validation and captcha

I have two issues with a contact form I have created. I was previously hit hard by spam.
I am requiring that all fields be filled out before the form is processed, but what I have written isn't working: info goes into the database whether a person fills out all fields or not. ***fixed by using:
function validateForm()
{
var x=document.forms["validation"]["firstname"].value;
if (x==null || x=="")
{
alert("Please enter your first name");
return false;
}
for all fields and this one for email:
var x=document.forms["validation"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Please enter a valid email address");
return false;
}
Now, I need to get the captcha working or how to add to check if captcha is correct in same javascript? I think the error lies in this somehow?:
session_start();
if($_POST['submitted'] == "contactus")
if( $_SESSION['security_code'] == $_POST['security_code'] && !empty($_SESSION['security_code'] ) ) {
header("Location:http://www.berrieswebdesign.com/thankyou.php?message=thanks");
unset($_SESSION['security_code']);
} else {
// Insert your code for showing an error message here
echo "<div id='thankyoubox'>'Security breach! Security Breach! Ehem...Your security code was incorrect.'</div>";
}
ob_flush();
?>
And lastly, here is contactfunctions.php
<?php ob_start();//Required for the redirect to work?>
<?php
include_once("databasefunctions.php");
$contactsdbtable = "contacts";
function GetHeaders()
{
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= "To: {$firstname} <{$email}>" . "\r\n";
$headers .= 'From: My Website <info#mywebsite.com>' . "\r\n";
return $headers;
}
function ContactMessage($firstname, $lastname, $email, $message, $location)
{
global $contactsdbtable;
openDatabase();
$firstname = mysql_real_escape_string($firstname);
$lastname = mysql_real_escape_string($lastname);
$email = mysql_real_escape_string($email);
$message = mysql_real_escape_string($message);
$location = mysql_real_escape_string($location);
$result = QuickQuery("INSERT INTO {$contactsdbtable}(firstname, lastname, email, message, location)
VALUES('{$firstname}', '{$lastname}', '{$email}', '{$message}', '{$location}')");
if($result)
{
$headers = GetHeaders();
$message = "\"Thank you for contacting us at My Website. We will be answering your website inquiry post haste.\"<br />
<br />
<br />
Best Regards,<br />
<br />
Me
";
mail($email, "RE: Design Inquiry", $message, $headers);
mail("myemail#blahblah.com", "Website Inquiry", "{$firstname}, {$email}, has sent a web design inquiry", $headers);
}
}
?>
I appreciate any help I receive on this in advance. Also, since this is a lengthy post, would you guys mind listing which issue you are addressing, 1 or 2?
Thanks!
Ok try this:
<?php
$is_error = false;
if($_POST['submitted'] == "contactus")
{
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$message = $_POST['message'];
$location = $_POST['location'];
if(!$firstname || $firstname = ''){
$error = "Please enter your first name.";
$is_error = true;
} else if(!$lastname || $lastname= ''){
$error = "Please enter your last name.";
$is_error = true;
} else if(!$email || $email= ''){
$error = "Please enter a valid email.";
$is_error = true;
}else if(!$message || $message= ''){
$error = "Please enter your message.";
$is_error = true;
}else if(!$location || $location= ''){
$error = "Please tell us where you're from.";
$is_error = true;
}
if(($is_error === false) && ($_SESSION['security_code'] == $_POST['security_code']))
{
ContactMessage($firstname, $lastname, $email, $message, $location);
} else {
Error($error);
}
}
?>

Email validation, using if else statements wont allow it to continue checking if there was an error with the first if?

I have:
if(isset($_POST['submit'])) {
if (empty($name)) {
echo'<span class="error">ERROR: Missing Name </span><br/>';
} else if(empty($phone) || empty($email)) {
echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
} else if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}
How else could I check for all of those issues without using else if?
When I use else if, it checks through the first if statement, if there is an issue with it it will not continue going through the other if statements following that one.
Any ideas? Thank you
You could collect all errors in an array like this:
if (isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = '<span class="error">ERROR: Missing Name </span><br/>';
}
if (empty($phone) || empty($email)) {
$errors[] = '<span class="error">ERROR: You must insert a phone number or email</span><br/>';
}
if (!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
$errors[] = '<span class="error">ERROR: Please Insert a valid Email</span><br/>';
}
if ($errors) {
echo 'There were some errors: ';
echo '<ul><li>', implode('</li><li>', $errors), '</li></ul>';
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name\n".
"Email: $email\n".
"Phone Number: $phone\n".
"Comment: $comment", "From: $email");
echo'<span id="valid">Message has been sent</span><br/>';
}
}
With this you can check all requirements and report all errors and not just the first one.
use:
$error = 0;
if(empty($var1)){ $error = 1; }
if(empty($var2)){ $error = 1; }
if(empty($var3)){ $error = 1; }
if(empty($var4)){ $error = 1; }
if(empty($var5)){ $error = 1; }
if($error > 0)
{
// Do actions for your errors
}
else
{
// Send Email
}
you can use try...catch statements for error checking like this.
whenever you encounter a condition where an error should be generated, you can use throw new Exception clause.
Use a dirty flag. Check them all and append the message to the dirty variable.
Try this:
if(isset($_POST['submit'])) {
$errors = array();
if (empty($name)) {
$errors[] = 'Missing Name';
}
if(empty($phone) || empty($email)) {
$errors[] = 'You must insert a phone number or email';
}
if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
$errors[] = 'Please Insert a valid Email';
}
if (!empty($errors)) {
for ($i = 0; i < count($errors); $i++) {
echo sprintf('<span class="error">ERROR: %s</span><br/>', $errors[$i]);
}
} else {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}
if(isset($_POST['submit'])) {
$valid = true;
if (empty($name)) {
echo'<span class="error">ERROR: Missing Name </span><br/>';
$valid = false;
}
if(empty($phone) || empty($email)) {
echo'<span class="error">ERROR: You must insert a phone number or email</span><br/>';
$valid=false;
}
if(!preg_match('/[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}/', $email)) {
echo'<span class="error">ERROR: Please Insert a valid Email</span><br/>';
$valid = FALSE;
}
if($valid) {
mail( "anEmail#hotmail.com", "Monthly Specials Email",
"Name: $name
Email: $email
Phone Number: $phone
Comment: $comment", "From: $email" );
echo'<span id="valid">Message has been sent</span><br/>';
}
}

Categories