I thought of using php header to redirect upon validation successful. However it's seems broken to me. How do I implement one then. Condition is when all the validation is validated then it would only redirect.
<?php
// define variables and set to empty values
$nameErr = $lastnameErr = $emailErr = $passwordErr = $confirmpasswordErr = $checkboxErr= "";
$name = $lastname = $email = $password = $confirmpassword = $checkbox = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["firstname"])) {
$nameErr = "First Name is required";
}else {
$name = test_input($_POST["firstname"]);
}
if (empty($_POST["lastname"])) {
$lastnameErr = "Last Name is required";
}else {
$name = test_input($_POST["lastname"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
}else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(!empty($_POST["password"]) && ($_POST["password"] == $_POST["confirmpassword"])) {
$password = test_input($_POST["password"]);
$confirmpassword = test_input($_POST["confirmpassword"]);
if (strlen($_POST["password"]) <= '8') {
$passwordErr = "Your Password Must Contain At Least 8 Characters!";
}
elseif(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number!";
}
elseif(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
}
elseif(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
}
elseif(empty($_POST["password"])) {
$passwordErr = "Password not filled at all";
}
elseif(!empty($_POST["password"])) {
$confirmpasswordErr = "Password do not match";
}
if(!isset($_POST['checkbox'])){
$checkboxErr = "Please check the checkbox";
}
else {
$checkbox = test_input($_POST["checkbox"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
header('Location: http://www.example.com/');
Set $error = 1 if any condition get failed , and at the bottom check if($error!=1) then redirect
and you can also use javascript redirect if header is not working
Look at the closing "?>"-Tab. header will generate a html-header, but is a php-function and should be inside the ?php ?> bracket.
Consider using html5 input validation - saves some code and server roundtrips to let the browser do the validation
Omit the closing "?>" altogether. Its not necessary and can lead to hard to see errors when there is content - even blanks - after the "?>"
Consider using the filter_input function with appropriate parameters to access $_POST and set your variables.
Related
I am trying to figure out how to redirect after validation of a form (i.e after conditions for my form have been met)(I have the header at the end of the PHP code). I have a basic form ,and I know this should be a straightforward code of line but I can't seem to make it work! Your advice is very much appreciated!
<?php
$firstNameErr = '';
$lastNameErr = '';
$emailErr='';
$passwordErr = '';
$passwordConfErr='';
if($_SERVER["REQUEST_METHOD"] == "POST"){
$firstName = $_POST["firstName"];
if(empty($firstName)){
$firstNameErr = "First Name is required";
}
else if(!preg_match("/^[a-zA-Z]+$/", $firstName)){
$firstNameErr= "Only letters, no spaces or special characters allowed";
}
else{
$firstNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$lastName = $_POST["lastName"];
if(empty($lastName)){
$lastNameErr = "Last Name is required";
}
else if(!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $lastName)){
$lastNameErr = "No Special characters or numbers allowed";
}
else{
$lastNameErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = $_POST["email"];
if(empty($email)){
$emailErr = "Email is required";
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$emailErr = "Invalid email format";
}
else{
$emailErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$password=$_POST["password"];
if(empty($password)){
$passwordErr = "Please Enter your password";
}
else if (strlen($password) < "8") {
$passwordErr = "Your Password Must Contain At Least 8 Digits !";
}
else if(!preg_match("#[0-9]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number !";
}
else if(!preg_match("#[A-Z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter !";
}
else if(!preg_match("#[a-z]+#",$password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter !";
}
else if(!preg_match('/[\'^£$%&*()}{##~?><>,|=_+¬-]/', $password)) {
$passwordErr = "Your Password Must Contain At Least 1 Special Character !";
}
else{
$passwordErr = "Valid";
}
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$confirmPassword = $_POST["confirmPassword"];
$password = $_POST["password"];
if(empty($confirmPassword)){
$passwordConfErr = "Please Enter your password";
}
else if($password!=$confirmPassword){
$passwordConfErr = "Passwords do not match";
}
else{
$passwordConfErr="Valid";
}
}
else{
echo "Form not submitted with POST";
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(isset($_POST['Register']) and $firstNameErr == "Valid" and $lastNameErr =="Valid" and $emailErr == "Valid" and $passwordErr == "Valid" and $passwordConfErr=="Valid") {
header("Location: profile.php");
exit();
}
}
A single if ($_SERVER["REQUEST_METHOD"] == "POST"){ which wraps all $_POST logic would suffice, then depending on your app (if its mostly AJAX) you should use a response/request flow so the POST logic is at the top and it falls through to the view with the errors which can then be used in the view, or you should return JSON and do an AJAX request, else you won't be able to pick up the errors unless you put them into the session and then pick them up on redirect which is just extra steps.
Example request/response, for a single page i.e register.php, this could be broken out where you load the HTML via an include or view loader but the idea is the same.
<?php
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
header("Location: profile.php");
exit();
}
// otherwise continue to form
} ?>
<form>
...
<input name="firstName" value="<?= htmlspecialchars($_POST['firstName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['firstName']) ? '<span class="form-error">'.$errors['firstName'].'</span>' : '' ?>
<input name="lastName" value="<?= htmlspecialchars($_POST['lastName'] ?? '', ENT_QUOTES, 'UTF-8') ?>"/>
<?= isset($errors['lastName']) ? '<span class="form-error">'.$errors['lastName'].'</span>' : '' ?>
</form>
Or if your going to use mostly AJAX, another way would be to return JSON, then you can access the errors to then build out the dom from the AJAX response.
<?php
//
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
// set json response header
header('Content-type: application/json;charset=utf-8');
// Is POST
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//
$errors = [];
// first name
if (empty($_POST["firstName"])){
$errors['firstName'] = "First Name is required";
} else if (!preg_match("/^[a-zA-Z]+$/", $_POST["firstName"])) {
$errors['firstName'] = "Only letters, no spaces or special characters allowed";
}
// last name
if (empty($_POST["lastName"])) {
$errors['lastName'] = "Last Name is required";
} else if (!preg_match("/^[A-Za-z]+((\s)?((\'|\-|)?([A-Za-z])+))*$/", $_POST["lastName"])) {
$errors['lastName'] = "No Special characters or numbers allowed";
}
// ...others
// errors is empty, so must all be valid
if (empty($errors)) {
// do something like insert into db and set session status
echo json_encode(['status' => 200]);
exit();
}
echo json_encode(['errors' => $errors]);
exit();
} else {
header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
echo json_encode(['status' => 405]);
}
} else {
header('Location: /');
}
In both examples, use a single errors array then its easy to access and all in one place. You also don't need to set additional vars from the $_POST['...'] vars to validate them.
Your validating code should look like this:
$Name = $Surname = $username = $password = $confirm_password =
$email ="";
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate Name.
if (empty(trim($_POST["firstName"]))) {
$errors[] = 'name required.';
} else {
$Name = $_POST["firstName"];
}
// Validate lastName.
if (empty(trim($_POST["lastName"]))) {
$errors[] = 'surname required.';
} else {
$Surname = $_POST["lastName"];
}
// Validate username
if (!preg_match("/^[a-zA-Z]+$/", $_POST["username"])) {
$errors['username'] = "Only letters, no spaces or special characters allowed";
}
// Validate username from database to see if username already exist.
//You can check for the email is well.
if(empty(trim($_POST["username"]))){
$errors[] = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT id FROM users WHERE username = :username";
if($stmt = $pdo->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bindParam(":username", $param_username, PDO::PARAM_STR);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if($stmt->execute()){
if($stmt->rowCount() == 1){
$errors[] = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
// Close statement
$stmt->closeCursor();
}
}
// Validate password
if(empty(trim($_POST["password"]))){
$errors[] = "Enter password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$errors[] = "password should be min 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$errors[] = "confirm pass.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if($password != $confirm_password){
$errors[] = "pass no matches.";
}
}
// Validate Email
if(filter_var($email, FILTER_VALIDATE_EMAIL)){
$email = $_POST["email"];
} else {
$errors[] = "invalid email type.";
}
// Validate Email
if(empty(trim($_POST["email"]))){
$errors[] = 'email required.';
}else {
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
}
if(empty($errors)){
//if no errors
//Do everythin else in here
//Do insert query after you are done redirect to profile page
header("Location: profile.php");
exit();
}
}
To get eroors :
<?php if(isset($errors)) {?>
<div class="error">
<?php echo implode('<br/>', $errors); ?>
</div>
<?php } unset($_SESSION['errors']); ?>
And your html form here if its in same page :
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
//inputs etc..
</form>
I have made this form where users can input various information,Everything is fine i am checking for different errors also but the problems is if user inputs email with a invalid email format and when pressing sumbit button it gives error invalid email format which is fine but mydatabase stores the invalid email also,How to prevent storing some invalid information?? And i am new to programming.
Thanks in advance.
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$nameErr = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$adressErr = "Adress is required";
}else{
$adress = $_POST["adress"];
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["password"])){
$passwordErr = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$genderErr = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
?>
Create a Boolean on top
$hasError = false;
In case of all error, set Boolean true as $hasError = true;
Before sql query :
if($hasError){
// redirect to form page -- pass the ERROR in the url as get and then show the error on form page
}
else{
// execute query code
}
It's good have server side checks, you can add a lot of validation on client side too.
Client side checks
For email, you can use type='email' instead of type='text'. Similarly, you can have maxlength, required, etc. to avoid erroneous data.
You first checked all field validation one by one and then executed your insert query. That's why always creating a new rows into database in both cases inputs are valid or invalid.
you should put your insertion query in the block if only inputs are valid.
Try this -
<?php
$nameErr = $adressErr = $emailErr = $passwordErr = $genderErr = "";
$name = $adress = $email = $password = $gender = "";
$error = array();
if(isset($_POST['sumbit'])){
if (empty($_POST["name"])){
$error[] = "Name is required";
}else{
$name = $_POST["name"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$error[] = "Only letters and white space allowed";
}
}
if(empty($_POST["adress"])){
$error[] = "Adress is required";
}else{
$error[] = $_POST["adress"];
}
if(empty($_POST["email"])){
$error[] = "Email is required";
}else{
$email = $_POST["email"];
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error[] = "Invalid email format";
}
}
if(empty($_POST["password"])){
$error[] = "Password is required";
}else{
$password = $_POST["password"];
}
if(empty($_POST["gender"])){
$error[] = "Gender is required";
}else{
$gender = $_POST["gender"];
}
}
if(empty($error)){
$sql = "INSERT INTO users(name,adress,email,password,gender)VALUES(:name,:adress,:email,:password,:gender)";
$statement = $conn->prepare($sql);
$statement->bindParam(":name",$name);
$statement->bindParam(":adress",$adress);
$statement->bindParam(":email",$email);
$statement->bindParam(":password",$password);
$statement->bindParam(":gender",$gender);
$statement->execute();
}else{
foreach ($error as $key => $value) {
echo '<li>'.$value.'</li>';
}
}
?>
I'm trying to get some form validations to work, but my script registers a user even if the data is incorrect and doesn't validate.
Also, what should I write so it can check whether the user is already in the database and return an error if so?
For example, if I just typed "aaaa" in all text boxes, it would register the user. What should happen if a user entered incorrect data (wrong format) is an error message should appear, and it should not register until the user enters correct data. But it registers the user no matter what I enter, as if there were no validations written.
<?php
include "db.php";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $passwordErr = $cpasswordErr = "";
$cpassword = "";
$cust_email = $cust_username = $cust_password = $cust_fullname = $cust_country = $cust_dob = $cust_gender = $cust_phone = "";
if (isset($_POST["btnsignup"])) {
//Username Validation
if (empty($_POST["txtcust_username"])) {
$nameErr = "Name is required";
} else {
$cust_username = test_input($_POST["txtcust_username"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z0-9]*$/", $cust_username)) {
$nameErr = "Only letters, numbers are allowed and no white space allowed";
}
}
//Email Validation
if (empty($_POST["txtcust_email"])) {
$emailErr = "Email is required";
} else {
$cust_email = test_input($_POST["txtcust_email"]);
// check if e-mail address is well-formed
if (!filter_var($cust_email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
//Password Validation
if (!empty($_POST["txtcust_password"]) && ($_POST["txtcust_password"] == $_POST["txtcust_cpassword"])) {
$cust_password = test_input($_POST["txtcust_password"]);
$cust_cpassword = test_input($_POST["txtcust_cpassword"]);
if (strlen($_POST["txtcust_password"]) <= '6') {
$passwordErr = "Your Password Must Contain At Least 6 Characters!";
} elseif (!preg_match("#[0-9]+#", $cust_password)) {
$passwordErr = "Your Password Must Contain At Least 1 Number!";
} elseif (!preg_match("#[A-Z]+#", $cust_password)) {
$passwordErr = "Your Password Must Contain At Least 1 Capital Letter!";
} elseif (!preg_match("#[a-z]+#", $cust_password)) {
$passwordErr = "Your Password Must Contain At Least 1 Lowercase Letter!";
}
} elseif (!empty($_POST["txtcust_password"])) {
$cpasswordErr = "Please Check You've Entered Or Confirmed Your Password!";
}
$cust_fullname = $_POST['txtcust_fullname'];
$cust_country = $_POST['txtcust_country'];
$cust_dob = $_POST['txtcust_dob'];
$cust_gender = $_POST['txtcust_gender'];
$cust_phone = $_POST['txtcust_phone'];
//Insert Into Table
$insert = "INSERT INTO customer (cust_email,cust_username,cust_password,cust_fullname,cust_country,cust_dob,cust_gender,cust_phone)
VALUES ('$cust_email','$cust_username','$cust_password','$cust_fullname','$cust_country','$cust_dob','$cust_gender','$cust_phone') ";
$run = mysqli_query($conn, $insert);
if ($run) {
setcookie("Name", $cust_username);
header("Location: home.php");
} else
echo "User has not been Add";
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
TL;DR You do a bunch of validation and set a bunch of error messages, but then ignore all of that and run the INSERT no matter what. Add an if/else statement to handle validation errors or do the insert.
Let's break this down. Your code isn't really a Minimal, Complete, and Verifiable Example, but we can make it into one. Stripping out all the unnecessary stuff, your code is basically this:
<?php
include "db.php";
// initializing some variables
// ...
// a bunch of validation stuff, where you set
// variables like $nameErr and $emailErr
// ...
// logic where you initialize $cust_fullname, $cust_country, etc.
// ...
/***************************************************************
* The database insertion, without ever checking whether
* the data validated!
***************************************************************/
//Insert Into Table
$insert = "INSERT INTO customer (cust_email,cust_username,cust_password,cust_fullname,cust_country,cust_dob,cust_gender,cust_phone)
VALUES ('$cust_email','$cust_username','$cust_password','$cust_fullname','$cust_country','$cust_dob','$cust_gender','$cust_phone') ";
$run = mysqli_query($conn,$insert);
// more code not relevant here...
?>
So, you just run the INSERT, regardless of what happens in the validation stage. There's your problem.
As for your second question (how to check for an existing user), that's a little broad for this site, and you generally should only ask one question at a time. Please try something first, then post that as a second question if you get stuck.
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.
I have a form, php validation, and send to email. My php validation works fine. My send to email works fine. When I use them both together, they work fine until I add header('Location: http://google.com'); exit(); I am using google.com for because I havent made my confirmation page yet. When I add this line to the php, that's when it goes straight to google.com when I go to my website. Can someone please help? I have been trying to figure out all of this validation and form to email for 2 straight days now, and I cannot figure it out. I know nothing about php. My code is below.
My php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if ( ! preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"])) {
$email2Err = "It is required to re-enter your email.";
} else {
$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if ( ! preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email2)) {
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"])) {
$commentsErr = "A comment is required.";
} else {
$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service'])) {
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
if (empty($errors)) {
$from = "From: Our Site!";
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to, $subject, $message, $from);
header('Location: http://google.com');
exit();
}
?>
Please someone help me. I have no idea what is wrong.
Ok. I did what you told me Barmar. Not sure if I did it right or not. It solved one problem, but another was created.
I started over with the code that validates and sends the form data to my email. Now I just want to add header('Location: http://google.com '); exit(); ....and it work. Can you tell me what to do? I have no idea what php, so the more specific that you can be, the better.
Here is the php:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $email2Err = $commentsErr = "";
$name = $email = $email2 = $comments = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}
}
if (empty($_POST["email2"]))
{$email2Err = "It is required to re-enter your email.";}
else
{$email2 = test_input($_POST["email2"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email2))
{
$email2Err = "Invalid email format";
}
}
if (empty($_POST["comments"]))
{$commentsErr = "A comment is required.";}
else
{$comments = test_input($_POST["comments"]);
if (preg_match("#^[a-zA-Z0-9 \.,\?_/'!£\$%&*()+=\r\n-]+$#", $comments)) {
// Everything ok. Do nothing and continue
} else {
$commentsErr = "Message is not in correct format.<br>You can use a-z A-Z 0-9 . , ? _ / ' ! £ $ % * () + = - Only";
}
}
if (isset($_POST['service']))
{
foreach ($_POST['service'] as $selectedService)
$selected[$selectedService] = "checked";
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($errors)) {
$from = "From: Our Site!"; //Site name
// Change this to your email address you want to form sent to
$to = "jasonriseden#yahoo.com";
$subject = "Mr Green Website | Comment from " . $name . "";
$message = "Message from " . $name . "
Email: " . $email . "
Comments: " . $comments . "";
mail($to,$subject,$message,$from);
}
?>
The problem is that there's no variable $errors. So if(empty($errors)) is always true, so it goes into the block that sends email and redirects. This happens even if the user hasn't submitted the form yet -- I'm assuming this code is part of the same script that displays the registration form after the code you posted.
You need to make two changes:
The code that sends the email and redirects should be moved inside the first if block, after all the validation checks.
Instead of if(empty($error)), it should check if($nameErr && $emailErr && $email2Err && $commentsErr). Or you should change the validation code to set $error whenever it's setting one of these other error message variables.
I know this isn't a direct answer to your question, but have a look into Exceptions. By having seperate functions for each validation and have them throw an exception when something is wrong, your code will be much cleaner and bugs will have much less room to pop up. Bonus points if you put all the validation functions in a class.
Example: (I renamed test_input() to sanitize_input(), because that's what it does)
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try
{
$name = getValidatedName();
$email = getValidatedEmail();
// send email with $name and $email
}
catch (Exception $e)
{
echo '<div class="error">' . $e->getMessage() . '</div>';
}
}
function getValidatedName()
{
if (empty($_POST["name"]))
throw new Exception("Name is required");
$name = sanitize_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/", $name))
throw new Exception("Only letters and white space allowed");
return $name;
}
function getValidatedEmail()
{
if (empty($_POST["email"]))
throw new Exception("Email is required");
$email = sanitize_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // you don't have to reinvent the wheel ;)
throw new Exception("Invalid email format");
return $email;
}