I am in the early stages of making a registration page for my website. However, the basic form I have created is being validated by javascript and php to ensure the right data will be entered. Even when the javascript is showing no errors and allowing the form to submit, the PHP errors are still being flagged and stopping it. below is the code for the php and html form. Any help will be greatly appreciated, these things are normally a lot easier than anticipated but its driving me crazy as it isnt showing any syntax errors just the errors that i have set up for the user.
The include files just have the mysql password and some basic functions for checking phone numbers.
Thanks in advance
HTML
<?php require_once("functions.inc"); ?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="register.js"></script>
<link rel="stylesheet" href="form.css">
<title>A Form</title>
</head>
<body>
<form id="userForm" method="POST" action="register-process.php">
<div>
<fieldset>
<legend>Registration Information</legend>
<div id="errorDiv">
<?php
if (isset($_SESSION['error']) && isset($_SESSION['formAttempt'])){
unset($_SESSION['formAttempt']);
print "errors encountered<br>\n";
foreach ($_SESSION['error'] as $error) {
print $error . "<br>\n";
}//end foreach
} // end if
?>
</div>
<label for="fname">First Name:* </label>
<input type="text" id="fname" name="fname">
<span class="errorFeedback errorSpan" id="fnameError">First Name is required</span>
<br>
<label for="name">Last Name:* </label>
<input type="text" id="lname" name="lname">
<span class="errorFeedback errorSpan" id="lnameError">Last Name is required</span>
<br>
<label for="email">Email Address:* </label>
<input type="text" id="email" name="email">
<span class="errorFeedback errorSpan" id="emailError">Email is required</span>
<br>
<label for="password1">Password:* </label>
<input type="password" id="password1" name="password1">
<span class="errorFeedback errorSpan" id="password1Error">Password is required</span>
<br>
<label for="password2">Varify Password:* </label>
<input type="password" id="password2" name="password2">
<span class="errorFeedback errorSpan" id="password2Error">Password's do not match</span>
<br>
<label for="addr">Address: </label>
<input type="text" id="addr" name="addr">
<br>
<label for="city">City: </label>
<input type="text" id="city" name="city">
<br>
<label for="state">State: </label>
<select name="state" id="state">
<option></option>
<option value="AL">Alabama</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="FL">Florida</option>
<option value="IL">Illinois</option>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="WI">Winconsin</option>
</select>
<br>
<label for="zip">ZIP: </label>
<input type="text" id="zip" name="zip">
<br>
<label for="phone">Phone Number: </label>
<input type="text" id="phone" name="phone">
<span class="errorFeedback errorSpan" id="phoneError">Format: xxx-xxx-xxxx</span>
<br>
<br>
<label for="work">Number Type:</label>
<input class="radioButton" type="radio" name="phoneType" id="work" value="work">
<label class="radioButton" for="work">Work</label>
<input class="radioButton" type="radio" name="phoneType" id="home" value="home">
<label class="radioButton" for="home">Home</label>
<span class="errorFeedback errorSpan phoneTypeError" id="phoneTypeError">Please Choose an option.</span>
<br>
<input type="submit" id="submit" name="submit">
</fieldset>
</div>
</form>
</body>
PHP register process.php
<?php
require_once('functions.inc');
//prevent access if they havent submitted the form!!
if (!isset($_POST['submit'])) {
die(header("location: register.php"));
}
$_SESSION['formAttempt'] = true;
if (isset($_SESSION['error'])) {
unset($_SESSION['error']);
}
$_SESSION['error'] = array();
$required = array("fname","lname", "email", "password1", "password2");
//check required fields!
foreach ($required as $requiredField) {
if (!isset($_POST[requiredField]) || $_POST[$requiredField] == "") {
$_SESSION['error'][] = $requiredField . " is required.";
}
}
if (!preg_match('/^[\w .]+$/',$_POST['fname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (!preg_match('/^[\w .]+$/',$_POST['lname'])) {
$_SESSION['error'][] = "Name must be letters and numbers only.";
}
if (isset($_POST['state']) && $_POST['state'] != "") {
if (!isValidState($_POST['state'])) {
$_SESSION['error'][] = "Please choose a valid state";
}
}
if (isset($_POST['zip']) && $_POST['zip'] != "") {
if (!isValidZip($_POST['zip'])) {
$_SESSION['error'][] = "ZIP code error";
}
}
if (isset($_POST['phone']) && $_POST['phone'] != "") {
if (!preg_match('/^[\d]+$/', $_POST['phone'])) {
$_SESSION['error'][] = "Phone numbner should be digits only.";
} else if (strlen($_POST['phone']) < 10 ) {
$_SESSION['error'] = "Phone number should be at least 10 digits.";
}
if (!isset($_POST['phoneType']) || $_POST['phoneType'] == "") {
$_SESSION['error'][] = "Please choose a phone type.";
} else {
$validPhoneTypes = array("work","home");
if (!in_array($_POST['phoneType'], $validPhoneTypes)) {
$_SESSION['error'][] = "Please choose a valid phone type";
}
}
}
if (!filter_var($_POST['email'],FILTER_VALIDATE_URL)) {
$_SESSION['error'][] = "Invalid e-mail address!";
}
if ($_POST['password1'] != $_POST['password2']) {
$_SESSION['error'] = "Passwords do not match";
}
//Final Disposition
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}");
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
The extension is the rest of the process php file, i have commented where the errors are coming from.... Thanks Again..
if (count($_SESSION['error']) > 0) {
die (header("Location: register.php"));
} else {
if (registerUser($_POST)) {
unset($_SESSION['formAttempt']);
die(header("Location: success.php"));
} else {
error_log("problem registering user: {$_POST['email']}"); // THIS IS WHERE THE ERROR IS COMNING FROM
$_SESSION['error'][] = "Problem registering account";
die(header("Location: register.php"));
}
}
function registerUser($userData) {
$mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
if ($mysqli->connect_errno) {
error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
return false;
}
$email = $mysqli->real_escape_string($_POST['email']);
//Check for an existing user
$findUser = "SELECT id from Customer where email = '{$email}'";
$findResult = $mysqli->query($findUser);
$findRow = $findResult->fetch_assoc();
if (isset($findRow['id']) && $findRow['id'] != "") {
$_SESSION['error'][] = "A user with that email already exists";
return false;
}
$lastname = $mysqli->real_escape_string($_POST['lname']);
$firstname = $mysqli->real_escape_string($_POST['fname']);
$cryptedPassword = crypt($_POST['password1']);
$password = $mysqli->real_escape_string($cryptedPassword);
if (isset($_POST['addr'])) {
$street = $mysqli->real_escape_string($_POST['addr']);
} else {
$street = "";
}
if (isset($_POST['city'])) {
$city = $mysqli->real_escape_string($_POST['city']);
} else {
$city = "";
}
if (isset($_POST['state'])) {
$state = $mysqli->real_escape_string($_POST['state']);
} else {
$state = "";
}
if (isset($_POST['zip'])) {
$zip = $mysqli->real_escape_string($_POST['zip']);
} else {
$zip = "";
}
if (isset($_POST['phone'])) {
$phone = $mysqli->real_escape_string($_POST['phone']);
} else {
$phone = "";
}
if (isset($_POST['phoneType'])) {
$phoneType = $mysqli->real_escape_string($_POST['phoneType']);
} else {
$phoneType = "";
}
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}
}
?>
Your query has a bug in it. Column count isn't the same as value count. You forgot to pass in $state.
$query = "INSERT INTO Customer (email,create_date,password,last_name,first_name,street,city,state,zip,phone,phone_type) " . "VALUES ('{$email}',NOW(),'{$password}','{$lastname}','{$firstname}'" . ",'{$street}','{$city}','{$state}', '{$zip}','{$phone}','{$phoneType}')";
if ($mysqli->query($query)) {
$id = $mysqli->insert_id;
error_log("inserted {$email} as ID {$id}");
return true;
} else {
error_log("Problem inserting {$query}");
error_log("Problem inserting {$mysqli->error}"); // log the error
$_SESSION['error'][] = "HERE"; // THIS IS WHERE THE ERROR IS COMNING FROM
return false;
}
Related
I have create a form with html and php that allows a user to create an account and their information is stored within a mysql database.
The forms works and the user is able to create an account. However if the user clicks the submit button without filling in the form it seems to display that the email address has already been added.
I can't seem to see what is wrong.
My php code
<?php
session_start();
error_reporting(E_ALL); ini_set('display_errors', 1);
include "connect.php";
if (isset($_POST["submit"])) {
$error = array(); // Declare An Array to store any error message
$title = $_POST['title'];
$address2 = $_POST['up_address2'];
if(empty($_POST['up_first_name'])) { // if no name has been supplied
$error[] = 'Please Enter Your First Name'; // add to array "error"
} else {
$firstName = $_POST['up_first_name']; // else assign it to a variable
}
if(empty($_POST['up_last_name'])) { // if no name has been supplied
$error[] = 'Please Enter Your Last Name'; // add to array "error"
} else {
$lastName = $_POST['up_last_name']; // else assign it to a variable
}
if(empty($_POST['up_email'])) { // if no name has been supplied
$error[] = 'Please Enter Your Email'; // add to array "error"
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*#([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['up_email'])) {
// regular expression for email validation
$email = $_POST['up_email'];
} else {
$error[] = 'Your email is invalid';
}
}
if(empty($_POST['up_password'])) {
$error[] = 'Please Enter Your Password';
} else {
$password = $_POST['up_password'];
}
if(empty($_POST['up_date_of_birth'])) {
$error[] = 'Please Enter Your Date Of Birth';
} else {
$dateOfBirth = $_POST['up_date_of_birth'];
}
if(empty($_POST['up_number'])) {
$error[] = 'Please Enter Your Contact Number';
} else {
$number = $_POST['up_number'];
}
if(empty($_POST['up_address'])) {
$error[] = 'Please Enter Your First Line of Your Address';
} else {
$address = $_POST['up_address'];
}
if(empty($_POST['up_country'])) {
$error[] = 'Please Enter Your Home Country';
} else {
$country = $_POST['up_country'];
}
if(empty($_POST['up_postcode'])) {
$error[] = 'Please Enter Your Postcode';
} else {
$postcode = $_POST['up_postcode'];
}
if(empty($error)) // send to Database if there's no error
{
// If everything is ok...
// Make sure the email address is avilable:
$query_verify_email = "SELECT * FROM user WHERE Email ='$email'";
$result_verify_email = mysqli_query($con, $query_verify_email);
if(!$result_verify_email) {
echo 'Database Error Occured';
}
if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email.
$query_insert_user = "INSERT INTO user (Title, FirstName, LastName, Email, Password, DataOfBirth, ContactNumber, Address, Address2, Country, Postcode)VALUES ('$title', '$firstName', '$lastName', '$email', '$password', '$dateOfBirth', '$number', '$address', '$address2', '$country', '$postcode')";
$result_insert_user = mysqli_query($con, $query_insert_user);
if (!$result_insert_user) {
echo 'Query Failed ';
}
} else { // If it did not run OK.
echo '<div class="errormsgbox">You could not be registered due to a system </div>';
}
} else { // The email address is not available.
echo '<div class="errormsgbox" >That email address has already been registered.</div>';
}
}
?>
My html form
<form name="signup" id="signup" action="create_account.php" method="post">
<label for="title">Title</label>
<select name="title" id="title">
<option value="Mr">Mr</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Dr">Dr</option>
</select>
<br>
<label for="up_first_name">First Name</label>
<input type="text" name="up_first_name" id="up_first_name" placeholder="First Name" />
<br>
<label for="up_last_name">Last Name</label>
<input type="text" name="up_last_name" id="up_last_name" placeholder="Last Name" />
<br>
<label for="up_email"> Email</label>
<input type="email" name="up_email" id="up_email" placeholder="username#email.com" />
<br>
<label for="up_password">Password</label>
<input type="password" name="up_password" id="up_password" placeholder="Password" />
<br>
<label for="up_date_of_birth">Date Of Birth</label>
<input type="text" name="up_date_of_birth" id="up_date_of_birth" placeholder="dd/mm/yyyy" />
<br>
<label for="up_number">Contact Number</label>
<input type="text" name="up_number" id="up_number" placeholder="+44 0000 000000" />
<br>
<label for="up_address">Address</label>
<input type="text" name="up_address" id="up_address" placeholder="Address" />
<br>
<label for="up_address2">Address 2 (optional)</label>
<input type="text" name="up_address2" id="up_address2" placeholder="Address 2" />
<br>
<label for="up_country">Country</label>
<input type="text" name="up_country" id="up_country" placeholder="Address 2" />
<br>
<label for="up_postcode">Postcode</label>
<input type="text" name="up_postcode" id="up_postcode" placeholder="Postcode" />
<br>
<input id="submit" name="submit" type="submit" value="Register My Account" id="myButton" class="btn btn-primary"/>
</form>
I have a form and all the validations, now I want to show the error messages in front of the text field not in the url. How do I do this?
Here is my PHP code:
<?php
if ((isset($_POST['submit']))){
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if(!empty($fullname)){
if (strlen($fullname) > 2 && strlen($fullname)<=30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
}else {$fmsg .="fullname can contain only alphabets <br>";}
}else{$fmsg1 .="fullname must be 2 to 30 char long <br>";}
}else{$fmsg2 .="fullname can not be blank <br>";}
if (!empty($email)) {
if (filter_var($email , FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con,$query2) or die("can not fire query".mysqli_error($con));
if (mysqli_num_rows($fire2)>0) {
$msg .=$email."is already taken please try another one<br> ";
}else{
$email_valid=true;
}
# code...
}else{$msg .=$email."is an invalid email address <br> ";}
# code...
}else{$msg .="email can not be blank <br>";}
if(!empty($username)){
if (strlen($username) > 4 && strlen($username)<=15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con,$query) or die("can not fire query".mysqli_error($con));
if(mysqli_num_rows($fire)> 0){
$umsg ='<p style="color:#cc0000;">username already taken</p>';
}else{
$username_valid = true;
}
# code...
# code...
}else {$msg.= "username can contain only alphabets <br>";}
}else{$msg.= "username must be 4 to 15 char long <br>";}
}else{$msg.="username can not be blank <br>";}
if (!empty($password)) {
if (strlen($password) >=5 && strlen($password) <= 15 ) {
$password_valid = true;
$password = md5($password);
# code...
}else{$msg .= $password."password must be between 5 to 15 character long<br>";}
# code...
}else{$msg .= "password can not be blank <br>";}
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con,$query) or die ("can not insert data into database".mysqli_error($con));
if ($fire){
header("Location: dashboard.php");}
}else{
header("Location: createaccount.php?msg=".$msg);
}
}
?>
and this is my html code:
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
</div>
<div>
<input type="submit" name="submit" id="submit"
value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
How do I get the error message in front of my text field, and also how do I get the specified error in front of the specified text field? I don't want to use ajax or javascript. I want to do it with PHP. I have tried this but no luck.
<?php if(isset($errorfname)) { echo $errorfname; } ?>
send msg to get params is not good idea.
Use session
$_SESSION['error_msg'] = $msg
header("Location: createaccount.php");
and add get error in php
$errors = '';
if(isset($_SESSION['error_msg'])) { $errors = $_SESSION['error_msg']; } ?>
and in html show $errors
By looking at your form does not have an action attribute therefore one can concluded that you are submitting the form at the same page as the form PHP_SELF
So if you want to display the error next to the field I would advice that you first declare an empty variables for each text error on top of your page then echo the variables next to each field.
<?php
$emailError = "";
$fullnameError = "";
$usernameError = "";
$passwordError = "";
$errors = 0;
if ((isset($_POST['submit']))) {
$email = strip_tags($_POST['email']);
$fullname = strip_tags($_POST['fullname']);
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$fullname_valid = $email_valid = $username_valid = $password_valid = false;
if (!empty($fullname)) {
if (strlen($fullname) > 2 && strlen($fullname) <= 30) {
if (!preg_match('/[^a-zA-Z\s]/', $fullname)) {
$fullname_valid = true;
# code...
} else {
$fullnameError = "fullname can contain only alphabets <br>";
$errors++;
}
} else {
$fullnameError = "fullname must be 2 to 30 char long <br>";
$errors++;
}
} else {
$fullnameError = "fullname can not be blank <br>";
$errors++;
}
if (!empty($email)) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$query2 = "SELECT email FROM users WHERE email = '$email'";
$fire2 = mysqli_query($con, $query2) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire2) > 0) {
$emailError = $email . "is already taken please try another one<br> ";
} else {
$email_valid = true;
}
# code...
} else {
$emailError = $email . "is an invalid email address <br> ";
$errors++;
}
# code...
} else {
$emailError = "email can not be blank <br>";
}
if (!empty($username)) {
if (strlen($username) > 4 && strlen($username) <= 15) {
if (!preg_match('/[^a-zA-Z\d_.]/', $username)) {
$query = "SELECT username FROM users WHERE username = '$username'";
$fire = mysqli_query($con, $query) or die("can not fire query" . mysqli_error($con));
if (mysqli_num_rows($fire) > 0) {
$usernameError = '<p style="color:#cc0000;">username already taken</p>';
$errors++;
} else {
$username_valid = true;
}
} else {
$usernameError = "username can contain only alphabets <br>";
$errors++;
}
} else {
$usernameError = "username must be 4 to 15 char long <br>";
$errors++;
}
} else {
$usernameError = "username can not be blank <br>";
$errors++;
}
if (!empty($password)) {
if (strlen($password) >= 5 && strlen($password) <= 15) {
$password_valid = true;
$password = md5($password);
# code...
} else {
$passwordError = $password . "password must be between 5 to 15 character long<br>";
$errors++;
}
# code...
} else {
$passwordError = "password can not be blank <br>";
$errors++;
}
//if there's no errors insert into database
if ($errors <= 0) {
if ($fullname_valid && $email_valid && $password_valid && $username_valid) {
$query = "INSERT INTO users(fullname,email,username,password,avatar_path) VALUES('$fullname','$email','$username','$password','avatar.jpg')";
$fire = mysqli_query($con, $query) or die("can not insert data into database" . mysqli_error($con));
if ($fire) {
header("Location: dashboard.php");
}
}
}
}
?>
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<div class="form-input">
<input name="email" type="email" name="email" id="email" placeholder="enter email" required="email is required">
<!-- display email error here -->
<?php echo $emailError?>
</div>
<input name="mobile" type="number" id="mobile" placeholder="enter mobile number" required="mobile is required">
<span id="message"></span>
<div class="form-input">
<input name="fullname" type="full name" id="fullname" name="full name" placeholder="full name" required="what's your fullname">
<?php echo $fullnameError?>
</div>
<div>
<input name="username" type="username" id="username" name="username" placeholder="username" required="username is required">
<?php echo $usernameError?>
</div>
<div>
<input name="password" type="password" id="password" name="password" placeholder="password" required="password is required">
<?php echo $passwordError?>
</div>
<div>
<input type="submit" name="submit" id="submit" value="sign up" class="btn btn-primary btn-block">
forgot password?
<h3>have an account? log in</h3>
</div>
</form>
NB: I would advice that you look into password_hash() and
password_verify()to hash your passwords, they provide better
security as compared tomd5()` and make sure your database column is
atleast 60 characters in length.. I would also advice to look into
prepared statements.
The following can help :
How can I prevent SQL injection in PHP?
Using PHP 5.5's password_hash and password_verify function
I think the best way is include from template in result
if ($fire){
header("Location: dashboard.php");
}else{
include("createaccount.php");
}
And in createaccount.php
<div class="container">
<form name="signup" id="signup" method="POST">
<h2>sign up</h2>
<p class="errors"><?= $msg ?></p>
...
how to pass the collected input to another page after self validate in php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
if($_SERVER["REQUEST_METHOD"] =="POST"){
$valid = true;
if(empty($_POST["forename"])){
$forenameErr = "Forename is required";
$valid = false; //false
} else {
$forename = test_input($_POST["forename"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["surname"])){
$surnameErr = "Surname is required";
$valid = false; //false
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["postalAddress"])){
$postalAddressErr =" Please enter postal address";
$valid = false; //false
} else {
$postalAddress = test_input($_POST["postalAddress"]);
}
if(empty($_POST["landLineTelNo"])){
$landLineTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$landLineTelNo = test_input($_POST["landLineTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$landLineTelNo)) {
$landLineTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["mobileTelNo"])){
$mobileTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$mobileTelNo = test_input($_POST["mobileTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$mobileTelNo)) {
$mobileTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
$valid = false; //false
} 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["sendMethod"])){
$sendMethodErr = "Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//if valid then redirect
if($valid){
header('Location: userdetail.php');
exit();
}
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error">* <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error">* <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> </span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> * <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" placeholder="example:012-3456789" value="<?php echo $mobileTelNo;?>" />
<span class="error"><?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>" placeholder="example:123#hotmail.com"/>
<span class="error"> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error">* <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="checkbox" value="check" id="agree" />
I have read and agree to the Terms and Conditions and Privacy Policy
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</fieldset>
</form>
</div>
</body>
</html>
here is my php form...
it can validate itself in the same page but couldn't pass the data to another php page....
here is my another php code...
<?php
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
echo "<p>Email: $email</p>";
echo "<p>Post Address: $postalAddress</p>";
echo "<p>Landline: $landLineTelNo</p>";
echo "<p>Mobile : $mobileTelNo</p>";
echo "<p>Contact method: $sendMethod";
?>
You can use $_SESSION variables.
PHP $_SESSIONS
PHP Sessions and Cookies
So after the users has been validated set $_SESSION['surname'] = $surname;
Then on the top of each page add session_start(); to the top.
Then Under that add
if (isset($_SESSION['surname'])) {
$surname = $_SESSION['surname'];
} else {
die();
}
View the PHP docs for a more thorough understanding.
You may also want to look into setting up a MYSQL database if you want users to be able to create accounts.
Edit: form page
if($valid){
$_SESSION['surname'] = $surname;
$_SESSION['postalAddress'] = $postalAddress;
header('Location: userdetail.php');
exit();
}
I have tried the following php script to validate the user input.But the form is sent to database without prompting the user to fill the required fields i.e if a user leaves one or more fields empty, the form is submitted without asking to fill the fields.How do stop it from submitting until the conditions for each form field are met?
here is the code:-
<?php
$fnameErr=$lnameErr=$emailErr=$passwordErr=$cpasswordErr="";
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
}
else
{
$fname = $_POST["fname"];
}
if (empty($_POST["lname"]))
{
$lnameErr = "Last Name is required";
}
else
{
$lname = $_POST["lname"];
}
if (empty($_POST["email"]))
{
$emailErr = "Email is required";
}
else
{
$email = $_POST["email"];
}
if (empty($_POST["password"]))
{
$passwordErr = "Password is required";
}
else
{
$password = $_POST["password"];
}
if (empty($_POST["cpassword"]))
{
$cpasswordErr = "Confirm Password";
}
else
{
$cpassword = $_POST["cpassword"];
}
//Create connection
$con=mysqli_connect("localhost","root","p11","daot");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO registration (FirstName, LastName, EmailAddress,Password,ConfirmPassword)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[password]','$_POST[cpassword]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mastercss.css">
<title>SIGN UP PAGE</title>
</head>
<body>
<?php include 'header.php'; ?>
<div class="leftbar">
</div>
<div class="content">
<h1 class="h1">complete the following form to register</h1>
<fieldset style="width:450px; background:gray;">
<form autocomplete="on" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="fname">First Name:</label>
<input type="text" name="fname"><?php echo $fnameErr;?><br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname"><?php echo $lnameErr;?><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><?php echo $emailErr;?><br><br>
<label for="password">Password:</label>
<input type="password" name="password"><?php echo $passwordErr;?><br><br>
<label for="cpassword">Confirm Password</label>
<input type="password" name="cpassword"><?php echo $cpasswordErr;?><br><br>
<!--<label for="sex">Sex</label><input type="radio" name="sex" value="female"> Female
<input type="radio" name="sex" value="male">Male<br>
<label for="select">Birthday</label>
<select name="birthday_Month" id="month">
<option value="0" selected="1">Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
</select>
<select name="birthday_day" id="month">
<option value="0" selected="1">Day</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select name="birthday_year" id="year">
<option value="0" selected="1">year</option>
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
</select><br><br>-->
<input type="submit" value="SIGN UP" style="width:100: height:100" name="Submit">
</form>
</fieldset>
</div>
<div class="rightbar"><br><br>
<a href="https://www.twitter.com"><img src="tw1.jpg">
<img src="fb2.jpg">
</div>
<?php include "footer.php";?>
</body>
</html>
The form is being submitted without showing validations because it is executing the following line of codes even after executing the validation conditions. You need to avoid executing of the code if any validation is not proper by exiting from the code segment.
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
exit;
}
You should do this instead
if(empty($_POST["fname"]))
{
$fnameErr="First name is Required";
echo $fnameErr;
exit();
}
and same for the rest of the conditions.
This will display all your errors at once:
In your PHP:
$error = array(); //save all errors into one array, later we will check if this array is empty to proceed with saving into DB
if(empty($_POST["fname"]))
{
$error['fname']="First name is Required";
}
else
{
$fname = $_POST["fname"];
}
if (empty($_POST["lname"]))
{
$error['lname'] = "Last Name is required";
}
else
{
$lname = $_POST["lname"];
}
if (empty($_POST["email"]))
{
$error['email'] = "Email is required";
}
else
{
$email = $_POST["email"];
}
if (empty($_POST["password"]))
{
$error['password'] = "Password is required";
}
else
{
$password = $_POST["password"];
}
if (empty($_POST["cpassword"]))
{
$error['cpassword'] = "Confirm Password";
}
else
{
$cpassword = $_POST["cpassword"];
}
if (empty($errors)) {
//if there are no errors, save into DB
//Create connection
$con=mysqli_connect("localhost","root","p11","daot");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO registration (FirstName, LastName, EmailAddress,Password,ConfirmPassword)
VALUES
('$_POST[fname]','$_POST[lname]','$_POST[email]','$_POST[password]','$_POST[cpassword]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
}
And in your HTML:
<label for="fname">First Name:</label>
//checking if error message is set, if yes display it
<input type="text" name="fname"><?php echo isset($error['fname'])?$error['fname']:'' ;?><br><br>
<label for="lname">Last Name:</label>
<input type="text" name="lname"><?php echo isset($error['lname'])?$error['lname']:'' ;?><br><br>
<label for="email">Email:</label>
<input type="email" name="email"><?php echo isset($error['email'])?$error['email']:'' ;?><br><br>
<label for="password">Password:</label>
<input type="password" name="password"><?php echo isset($error['password'])?$error['password']:'' ;?><br><br>
<label for="cpassword">Confirm Password</label>
<input type="password" name="cpassword"><?php echo isset($error['cpassword'])?$error['cpassword']:'' ;?><br><br>
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
EDIT/UPDATE:
I moved my php code from my process.php file to the top of my contact.php file and it worked. So what am I missing from the process.php file that is not redirecting it back to the contact.php page?
This is my html in contact.php
<?php echo $message; ?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
And this is my process.php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
}
}
It is not working. Also the html5 validation isn't even working either. Is there something wrong with my form markup?
When you click on submit, your browser navigates to process.php. All of the code from contact.php is forgotten and a new page is generated.
There is no implied link between the two pages. The messages from process.php will not apppear on contact.php. Currently, process.php doesn't echo anything, so you're probably arriving at a blank page.
An alternate way to do this would be to merge the two pages like this:
<?php
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
//don't clear this, you need this to re-populate the page below
//unset($_POST);
}
}
?><!doctype html>
<html>
<head>
...
</head>
<body>
<?php echo $message; ?>
<form action="contact.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" required/>
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" required/><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" required/><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" required/>
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" required/>
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" required/>
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" required/>
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php echo $success_message; ?>
</form>
</body>
</html>
The $message and $success_message variables are now saved and they should display in the page markup below.
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
//when submit has been pressed, begin form validate
if(isset($_POST['submit'])) {
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message = "Please include your first name. ";
echo $message;
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message = "Please include your last name. ";
echo $message;
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message = "Please include your billing address. ";
echo $message;
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message = "Please enter a city. ";
echo $message;
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message = "Please select a state. ";
echo $message;
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message = "Please include a zip code. ";
echo $message;
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message = "Please include your phone number. ";<
echo $message;
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message = "A valid email is required. ";
echo $message;
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message = "You forgot to select a service package. ";
echo $message;
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
echo $success_message;
//clear form when submission is successful
unset($_POST);
}
}
i added echo $message for echoing during validation and .= was i think wrong way, otherwise you would have a message that contains all error messages..
Try adding this after the unset( $_POST ) line:
header('Location: contact.php');
That should take you back to the contact.php page.
EDIT:
However, in order for your code completely to work the way you want it, here what I would do.
<?php
session_start();
if (isset ($_SESSION['message'])) {
echo $_SESSION['message'];
session_destroy();
}
?>
<form action="process.php" method="post" name="sign_up">
<input type="text" name="first_name" placeholder="First Name" value="<?php echo $_POST[first_name]; ?>" />
<input type="text" name="last_name" placeholder="Last Name" value="<?php echo $_POST[last_name]; ?>" /><br>
<label class="bill-address">Billing Address:<br>
<input type="text" name="address1" placeholder="Address 1" value="<?php echo $_POST[address1]; ?>" /><br>
<input type="text" name="address2" placeholder="Address 2" value="<?php echo $_POST[address2]; ?>" /><br>
<input type="text" name="city" placeholder="City" value="<?php echo $_POST[city]; ?>" />
</label>
<?php
$state_list = array('AL'=>"Alabama",
'AK'=>"Alaska",
'AZ'=>"Arizona",
'AR'=>"Arkansas",
'WV'=>"West Virginia",
'WI'=>"Wisconsin",
'WY'=>"Wyoming");
?>
<select name="state">
<?php
while(list($k,$v) = each($state_list)) {
$selected = '';
if ($k == $_POST[state]) {
$selected = ' selected="true"';
}
echo "<option value=\"$k\"$selected>$v</option>\n";
}
?>
</select>
<input type="text" name="zip" placeholder="Zip Code" value="<?php echo $_POST[zip]; ?>" />
<br style="clear: left;" />
<input type="email" name="email" placeholder="you#youremail.com" value="<?php echo $_POST[email]; ?>" />
<input type="tel" name="phone" placeholder="Phone" value="<?php echo $_POST[phone]; ?>" />
<h3>Choose your Package</h3>
<select name="package">
<option value="Free">Free!</option>
<option value="Basic">Basic</option>
<option value="Corporate">Corporate</option>
<option value="Enterprise">Enterprise</option>
<option value="Enterprise_20">Enterprise 20</option>
<option value="Enterprise_50">Enterprise 50</option>
<option value="Enterprise_100">Enterprise 100</option>
</select>
<h3>Add Media Package?</h3>
<input type="radio" name="Yes" value="yes" />Yes
<input type="radio" name="No" value="no" />No
<button type="submit" class="btn">Send »</button>
<?php
//session already started on line 2
if (isset( $_SESSION['success'] )) {
echo $_SESSION['success'];
session_destroy();
}
?>
</form>
That's for contact.php, and
<?php
//when submit has been pressed, begin form validate else return to contact.php
if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" ) {
session_start();
//validate email
function is_valid_email($email) {
$result = true;
$pattern = '/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i';
if(!preg_match($pattern, $email)) {
$result = false;
}
return $result;
}
$valid = true;
$message = '';
if ( $_POST['first_name'] == "" ) {
$message .= "Please include your first name. ";
$valid = false;
}
if ( $_POST['last_name'] == "" ) {
$message .= "Please include your last name. ";
$valid = false;
}
if ( $_POST['address1'] == "" ) {
$message .= "Please include your billing address. ";
$valid = false;
}
if ( $_POST['city'] == "" ) {
$message .= "Please enter a city. ";
$valid = false;
}
if ( $_POST['state'] == "" ) {
$message .= "Please select a state. ";
$valid = false;
}
if ( $_POST['zip'] == "" ) {
$message .= "Please include a zip code. ";
$valid = false;
}
if ( $_POST['phone'] == "" ) {
$message .= "Please include your phone number. ";
$valid = false;
}
if ( !is_valid_email($_POST['email']) ) {
$message .= "A valid email is required. ";
$valid = false;
}
if ( $_POST['package'] == "" ) {
$message .= "You forgot to select a service package. ";
$valid = false;
}
if ( $valid == true ) {
$success_message = 'Brilliant I say! We will be in contact with you shortly.';
//clear form when submission is successful
unset($_POST);
$_SESSION['success']=$success_message;
}
else {
$_SESSION['message'] = $message;
}
header('Location: contact.php');
} // end of if ( $_SERVER[ 'REQUEST_METHOD' ] == "POST" )
else header('Location: contact.php');
?>
process.php
The following control I think was creating the biggest confusion in your code:
//when submit has been pressed, begin form validate
if(isset($_POST['submit']))
as soon as I replaced it, everything started to work better.