php form validation: if no errors echo"working" - php

Thank you in advance, I am trying to figure out why my code isn't running the
if($error != true) {
echo "working";} block of code. I wish to replace this with mysql functionality later on but for now i need to know how to get the form submission working when all the fields are valid.
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$error = $fnameErr = $lnameErr = $doberror = $SnameErr = $state_Err = $post_code_num_Err = $sex_Err= $emailErr = $pwd1 = "";
$fname = $lname = $dob = $street_name = $state =$post_code_num = $sex = $email = $pwd1_Err = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["fname"])) {
$fnameErr = "Name is required";
$error = true;
} else {
$fname = test_input($_POST["fname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$fname)) {
$error = true;
$fnameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["lname"])) {
$lnameErr = "last name is required";
$error = true;
} else {
$lname = test_input($_POST["lname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lname)) {
$lnameErr = "Only letters and white space allowed";
$error = true;
}
}
if (empty($_POST["dob"])) {
$doberror = "dob name is required";
$error = true;
} else {
$dob = test_input($_POST["dob"]);
// check if name only contains letters and whitespace
if (!preg_match("/^(0?[1-9]|[12]\d|3[01])\/(0?[1-9]|1[012])\/(19|20)\d\d$/",$dob)) {
$doberror = "format must match dd/mm/yyyy";
$error = true;
}
}
if (empty($_POST["street_name"])) {
$SnameErr = "street name is required";
$error = true;
} else {
$street_name = test_input($_POST["street_name"]);
// check if name only contains letters and whitespace
if (!preg_match("/\d{1,3}.?\d{0,3}\s[a-zA-Z]{2,30}\s[a-zA-Z]{2,15}/",$street_name)) {
$SnameErr = "must be in format like 123 fake street or 12/2 fake street";
$error = true;
}
}
if (empty($_POST["state"])) {
$state_Err = "state is required";
$error = true;
} else {
$state = test_input($_POST["state"]);
$error = true;
}
if (empty($_POST["post_code_num"])) {
$post_code_num_Err = "Post code is required";
$error = true;
} else {
$post_code_num = test_input($_POST["post_code_num"]);
// check if name only contains letters and whitespace
if (!preg_match("/^\d{4,4}$/",$post_code_num)) {
$post_code_num_Err = "4 digit postcode only";
$error = true;
}
}
if (empty($_POST["sex"])) {
$sex_Err = "Gender is required";
$error = true;
} else {
$sex = test_input($_POST["sex"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
$error = true;
} 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";
$error = true;
}
}
if (empty($_POST["pwd1"])) {
$pwd1 = "password is required";
$error = true;
} else {
$pwd1 = test_input($_POST["pwd1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}$/",$pwd1)) {
$pwd1_Err = "Must contain at least one number, one lowercase and one uppercase letter. must have a minimum of 6 characters";
$error = true;
}
}
if($error != true) {
echo "working";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo ($_SERVER["testphp.php"]);?>">
First Name:<br>
<input type="text" name="fname" value="<?php echo $fname;?>">
<span class="error">* <?php echo $fnameErr;?></span>
<br>
Last Name:<br>
<input type="text" name="lname" value="<?php echo $lname;?>">
<span class="error">* <?php echo $lnameErr;?></span>
<br>
Date of Birth:<br>
<input type="text" name="dob" value="<?php echo $dob;?>">
<span class="error">* <?php echo $doberror;?></span>
<br>
<fieldset>
<br>
<legend>Address:</legend>
<br>
Street Name:
<input type="text" name="street_name" value="<?php echo $street_name;?>">
<span class="error">* <?php echo $SnameErr;?></span>
<br>
State:
<select name="state" id="state" placeholder="Select a state"
<option value="">Please Select</option>
<option value="QLD">QLD</option>
<option value="NT">NT</option>
<option value="WA">WA</option>
<option value="SA">SA</option>
<option value="NSW">NSW</option>
<option value="ACT">ACT</option>
<option value="TAS">TAS</option>
<option value="VIC">VIC</option>
</select>
<span class="error">* <?php echo $state_Err;?></span>
<br>
Post Code:
<input type="text" name="post_code_num" value="<?php echo $post_code_num;?>">
<span class="error">* <?php echo $post_code_num_Err;?></span>
</fieldset>
<br>
Sex:
<input type="radio" name="sex" value="male" checked>Male
<input type="radio" name="sex" value="female">Female
<span class="error">* <?php echo $sex_Err;?></span>
<br>
Email:
<input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br>
password:
<input type="password" name="pwd1" value="<?php echo $pwd1;?>">
<span class="error">* <?php echo $pwd1_Err;?></span>
<br>
<input type="submit"></input>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $house_num;
echo "<br>";
echo $street_name;
echo "<br>";
echo $state;
echo "<br>";
echo $post_code_num;
echo "<br>";
echo $dob;
echo "<br>";
echo $sex;
echo "<br>";
echo $email;
echo "<br>";
echo $pwd1;
echo "<br>";
?>
</body>

if (empty($_POST["state"])) {
$state_Err = "state is required";
$error = true;
} else {
$state = test_input($_POST["state"]);
$error = true;
}
So always $error=true.

Related

Using Parameterized Queries/Prepared Statements

I'm new to php coding and have been told by others that I need to be using parameterized queries/prepared statements for my php scripts and MySQL database. I've looked at other examples of scripting these prepared statements and they usually refer to user login functions. My query is just a web form to capture user inputted data and store in database (SQL insert as opposed to SQL select). I am hoping someone can help me with how to script the php to prevent sql injections. Also hoping someone can let me know whether these prepared statements should also be used in php SQL Select scripts where I am only displaying database records on a form. Thanks in advance!
Here are the two php files I am using, the first is my database connection script:
<?php
DEFINE ('DB_USER', 'fakeuser');
DEFINE ("DB_PSWD", 'fakepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'newspaper');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
Web form PHP script:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} 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";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} 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";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die(mysqli_error($dbcon)); //and die('error inserting new record') ;
} // end of nested if statement
// else
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
UPDATED CODE with Prepared Statement 9/3/17: See bottom of script (Please tell me if you see any issues with this) Also I've commented out the !mysqli_query IF statement below the prepared statement as I thought this was now redundent, but please tell me if it is still required.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
$errors = "false";
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$nameErr = "Name is required";
$errors = "true";
} 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";
$errors = "true";
}
}
if (empty($_POST["Email"])) {
$emailErr = "Email is required";
$errors = "true";
} 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";
$errors = "true";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
$errors = "true";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required";
$errors = "true";
}
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
if (isset($_POST['submitted']) && $errors == "false")
{
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES (?,?,?,?)";
$stmt = mysqli_stmt_init($dbcon);
if (!mysqli_stmt_prepare($stmt,$sqlinsert)) {
echo "SQL error"; }
else {
mysqli_stmt_bind_param($stmt,"ssss",$fname, $femail, $fcomment, $fsubsciption);
mysqli_stmt_execute($stmt);
echo '1 record added to the database';
//if (!mysqli_query($dbcon, $sqlinsert)) {
//die(mysqli_error($dbcon));
} // end of nested IF statement
// else
//$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>

Defined Variable in PHP script has undefined variable error

I'm recieving an issue in the following php code. I am recieiving an unknown variable error in line 146, (echo $newrecord) variable. I'm not sure what is wrong with this variable, I have defined it in the IF statement, and am simply echoing if it is successful. I originally had that segment of code (after ) at the top of the script, but it was causing issues with the mandatory field error messages displaying properly. Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = $subErr = "";
$name = $email = $gender = $comment = $website = $sub = $newrecord = "";
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 is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["Website"])) {
$website = "";
} else {
$website = test_input($_POST["Website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}
if (empty($_POST["Comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["Comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
if (empty($_POST["Subscription"])) {
$subErr = "Subscription is required"; }
else {
$sub = test_input($_POST["Subscription"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Southern Tier Daily News</h2>
<form method="post" action="Newspaper3.php">
<input type="hidden" name="submitted" value="true"/>
<img src="https://bloximages.newyork1.vip.townnews.com/dnews.com/content/tncms/custom/image/5eec4204-483e-11e6-93c8-97ef236dc6c5.jpg?_dc=1468334339" alt="HTML5 Icon" style="width:128px;height:128px;">
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Newspaper Subscription Request</legend>
Name: <input type="text" name="Name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="Email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="Website" value="<?php echo $website;?>">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="Comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
Subscription:
<select name="Subscription">
<option value=""></option>
<option value="Daily">Daily</option>
<option value="Evening">Evening</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
</select>
<span class="error">* <?php echo $subErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
<br><br>
Visit Admin Page
</fieldset>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "<br>";
echo $sub;
?>
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['Name'];
$femail = $_POST['Email'];
$fcomment = $_POST['Comment'];
$fsubsciption = $_POST['Subscription'];
$sqlinsert = "INSERT INTO newspaper (Name, Email, Comment, Subscription) VALUES ('$fname',
'$femail', '$fcomment', '$fsubsciption')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} // end of nested if statement
$newrecord = "1 record added to the database";
} // end of main if statement
?>
<?php
echo $newrecord
?>
</body>
</html>
newrecord is defined and initialized inside the if statement, therefore if your code opts to the else, it will skip the if and your newrecord variable won't exist.
$newrecord is defined within an if statement, when the if is not executed the variable is not available. You can define it by default adding $newrecord = ''; before you start the if for the submit.

PHP How to submit form, if there are no errors. no javascript

I have separate email script; however, how would we run that code if there are no errors. I have a array with form errors $errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr); but they have different strings, if there are no strings or Null or '' inside the array, we would like to send email.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$name = $phone = $email = $zip = $service = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "letters and spaces only.";
}
}
if (empty($_POST["email"])) {
$emailErr = "email 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["phone"])) {
$phoneErr = "phone required.";
} else {
//Check phone for numbers () or - only
$phone = test_input($_POST["phone"]);
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $phone)) {
$phoneErr = "format.";
}
}
if (empty($_POST["zip"])) {
$zipErr = "zip required.";
} else {
$zip = test_input($_POST["zip"]);
}
if (!preg_match("/^[\+0-9\-\(\)\s]*$/", $zip)){
$zipErr = "format.";
}
if ($_POST["service"] == NULL ) {
$serviceErr = "service required.";
}else {
$service = test_input($_POST["service"]);
}
$comment = test_input($_POST["comment"]);
//**********************************************************************
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
//if no errors run send email CODE.
}
//***********************************************************************
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table>
<tr>
<td> Name:
<br />
<input name="name" type="text" size="20" value="<?php echo $name;?>">
<span class="error">* <?php echo "<br />"; echo $nameErr;?></span>
</td>
</tr>
<tr>
<td> Phone:
<br />
<input name="phone" type="text" size="20" value="<?php echo $phone;?>">
<span class="error">* <?php echo "<br />"; echo $phoneErr;?></span>
</td>
</tr>
<tr>
<td> E-mail:
<br />
<input name="email" type="text" size="20" value="<?php echo $email;?>">
<span class="error">* <?php echo "<br />"; echo $emailErr;?></span>
</td>
</tr>
<tr>
<td> Zip:
<br />
<input name="zip" type="text" size="20" value="<?php echo $zip;?>">
<span class="error">* <?php echo "<br />"; echo $zipErr;?></span>
</td>
</tr>
<tr>
<td> Service:
<br />
<select name="service">
<option selected="selected" value="<?php echo $service;?>"><?php echo $service;?></option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
<span class="error">* <?php echo "<br />"; echo $serviceErr;?></span>
</td>
</tr>
<tr>
<td> Message:
<br />
<textarea name="comment" rows="2" cols="20"><?php echo $comment;?></textarea></td>
</tr>
<tr>
<td>
<input type="submit" name="Submit" value="Send" />
</td>
</tr>
</table>
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $phone;
echo "<br>";
echo $zip;
echo "<br>";
echo $service;
echo "<br>";
echo "$comment";
?>
</body>
</html>
try with the below code:
$errors = array($nameErr, $emailErr, $phoneErr, $zipErr, $serviceErr);
if (isset($_POST['Submit'])) {
if(!array_filter($errors)){
// code here
}
else {
echo "Error";
}
}
Save your errors in an array, then check if the array is empty at the end. If so, no errors - submit email. Else, display errors:
//dont declare separate variables,use an array
//$nameErr = $phoneErr = $emailErr = $zipErr = $serviceErr = "";
$errors = [];
if (empty($_POST["name"])) {
$errors['nameErr'] = "name required.";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$errors['nameErr'] = "letters and spaces only.";
}
}
//other validation here, then
if(empty($errors){
//no errors, submit
your_submit_function();
}else{
//display errors
foreach($errors as $val){
echo $val . '<br/>';
}
}

Redirect to new page after PHP validation

I am very new to php and have been working on a website which contains a form for a restaurant reservation. Currently, I have one file, which contains both html and php code. The form is validated once the user clicks submit, however I was wondering how it might be possible to redirect the user to a new page, confirming their reservation, if all of the information they have entered into the form is correct.
Basically this is the process I wish the website to perform:
user fills out form
if validation not complete
display error messages, loop back to form so user can correct fields
if form is validated fully
Send user to confirmation page
Here is the necessary code for my reservations page:
....
<?php
$nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
$name = $tele = $email = $party = $vip = $reservation = $time = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter a full name";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid name entered";
}
}
if (empty($_POST["tele"])) {
$teleErr = "Please enter a telephone number";
} else {
$tele = test_input($_POST["tele"]);
if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
$teleErr = "Invalid telephone number entered";
}
}
if (empty($_POST["email"])) {
$emailErr = "Please enter an email address";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email entered";
}
}
if($_POST['party']=="") {
$partyErr = "Please select the party size";
} else {
$party = test_input($_POST["party"]);
}
if (empty($_POST["vip"])) {
$vipErr = "Please make a VIP area selection";
} else {
$vip = test_input($_POST["vip"]);
}
if (empty($_POST["reservation"])) {
$reservationErr = "Please enter the reservation date";
} else {
$reservation = test_input($_POST["reservation"]);
if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
$reservationErr = "Invalid reservation date";
}
}
if($_POST['time']=="") {
$timeErr = "Please select the reservation time";
} else {
$time = test_input($_POST["time"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<body>
<div id= "container">
<div id="header">
<div id="logo">
<img src="Steakhouselogo.png" width="440" height="152" alt="This is an image of the Steakhouse® logo">
</div>
<br>
<p class="slogan"> <strong> Welcome to Steakhouse®, the number 1 restaurant for flame grilled goodness. </strong> </p>
</div>
<div id="links">
<ul class="nav">
</ul>
</div>
<br>
<!-- Introduction of HTML form -->
<div id="body">
<h1> Book a Table </h1>
<br><br>
<br>
<div class="view">
<img src="view.png" width="451" height="227" alt="A view of our restaurant">
</div>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<!-- Personal information -->
<div class="form">
<div class="indicates">
<br>
* indicates a required field
</div>
<p class="ex">
<br><br>
<strong> Full Name* : </strong> <br> <input type="text" placeholder="John Doe" name="name" value="<?php echo $name;?>">
<span class="error"> <?php echo $nameErr;?></span>
<br><br><br>
<strong> Contact Telephone* : </strong> <br> <input type="text" placeholder="Telephone Number" name="tele" value="<?php echo $tele;?>">
<span class="error"><?php echo $teleErr;?></span>
<br><br><br>
<strong> Contact Email* : </strong> <br> <input type="text" placeholder="Example#email.com" name="email" value="<?php echo $email;?>">
<span class="error"><?php echo $emailErr;?></span>
<br><br>
<!-- Party requirments -->
<br>
<strong>Select Party Size* :</strong>
<br>
<select name="party" id="party" value="<?php echo $party;?>">
<option value="">Please Select</option>
<option <?php if (isset($party) && $party=="5") echo "selected";?> value="5">1 Person (+£5)</option>
<option <?php if (isset($party) && $party=="10") echo "selected";?> value="10">2 People (+£10)</option>
<option <?php if (isset($party) && $party=="15") echo "selected";?> value="15">3 People (+£15)</option>
<option <?php if (isset($party) && $party=="20") echo "selected";?> value="20">4 People (+£20)</option>
<option <?php if (isset($party) && $party=="25") echo "selected";?> value="25">5 People (+£25)</option>
<option <?php if (isset($party) && $party=="30") echo "selected";?> value="30">6 People (+£30)</option>
<option <?php if (isset($party) && $party=="35") echo "selected";?> value="35">7 People (+£35)</option>
<option <?php if (isset($party) && $party=="40") echo "selected";?> value="40">8 People (+£40)</option>
<option <?php if (isset($party) && $party=="45") echo "selected";?> value="45">9 People (+£45)</option>
<option <?php if (isset($party) && $party=="50") echo "selected";?> value="50">10+ People (+£50)</option>
</select>
<span id="party" class="error"><?php echo $partyErr;?></span>
<br><br><br>
<strong>Dietary Requirements:</strong>
<br><br>
Vegetarian <input type="checkbox" name="diet[]" value="Vegetarian">
<br><br>
Vegan <input type="checkbox" name="diet[]" value="Vegan">
<br><br>
Peanut Allergy <input type="checkbox" name="diet[]" value="Peanut Allergy">
<br><br>
Gluten Allergy <input type="checkbox" name="diet[]" value="Gluten Allergy">
<br><br><br>
<strong> VIP area* : </strong> <br><br>
Yes (+£5) <input type="radio" name="vip" <?php if (isset($vip) && $vip=="Yes") echo "checked";?> value="Yes">
<br><span id="vip" class="error"><?php echo $vipErr;?></span><br>
No <input type="radio" name="vip" <?php if (isset($vip) && $vip=="No") echo "checked";?> value="No">
<br><br><br>
<strong> Reservation Date* : </strong> <br> <input type="text" placeholder="DD/MM/YYYY" name="reservation" value="<?php echo $reservation;?>">
<span class="error"><?php echo $reservationErr;?></span>
<br><br><br>
<strong> Reservation Time* : </strong>
<br>
<select name="time" value="<?php echo $time;?>">
<option value="">Please Select</option>
<option <?php if (isset($time) && $time=="17:00") echo "selected";?> value="17:00">17:00</option>
<option <?php if (isset($time) && $time=="17:30") echo "selected";?> value="17:30">17:30</option>
<option <?php if (isset($time) && $time=="18:00") echo "selected";?> value="18:00">18:00</option>
<option <?php if (isset($time) && $time=="18:30") echo "selected";?> value="18:30">18:30</option>
<option <?php if (isset($time) && $time=="19:00") echo "selected";?> value="19:00">19:00</option>
<option <?php if (isset($time) && $time=="19:30") echo "selected";?> value="19:30">19:30</option>
<option <?php if (isset($time) && $time=="20:00") echo "selected";?> value="20:00">20:00</option>
<option <?php if (isset($time) && $time=="20:30") echo "selected";?> value="20:30">20:30</option>
<option <?php if (isset($time) && $time=="21:00") echo "selected";?> value="21:00">21:00</option>
<option <?php if (isset($time) && $time=="21:30") echo "selected";?> value="21:30">21:30</option>
<option <?php if (isset($time) && $time=="22:00") echo "selected";?> value="22:00">22:00</option>
</select>
<span id="time" class="error"><?php echo $timeErr;?></span>
<br><br><br>
<strong> Any Additional Information: </strong>
<br>
<textarea name="comments" placeholder="Birthdays, Class Parties..." rows="7" cols="40"></textarea>
<br><br>
<div class="totalPrice">
The total reservation price will be calculated automatically once submitted.
<br><br><br>
</div>
<div class="submitEtc">
<input type="submit" id="submit" name="submit" value="Submit">
<input type="reset" value="Reset form">
<br><br><br><br>
....
I have put a lot of effort into my work thus far, so any suggestions are welcomed. Please remember I am new to web languages also. Thank you.
Here is your code
<?php
$nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
$name = $tele = $email = $party = $vip = $reservation = $time = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter a full name";
} else {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid name entered";
}
}
if (empty($_POST["tele"])) {
$teleErr = "Please enter a telephone number";
} else {
$tele = test_input($_POST["tele"]);
if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
$teleErr = "Invalid telephone number entered";
}
}
if (empty($_POST["email"])) {
$emailErr = "Please enter an email address";
} else {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email entered";
}
}
if($_POST['party']=="") {
$partyErr = "Please select the party size";
} else {
$party = test_input($_POST["party"]);
}
if (empty($_POST["vip"])) {
$vipErr = "Please make a VIP area selection";
} else {
$vip = test_input($_POST["vip"]);
}
if (empty($_POST["reservation"])) {
$reservationErr = "Please enter the reservation date";
} else {
$reservation = test_input($_POST["reservation"]);
if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
$reservationErr = "Invalid reservation date";
}
}
if($_POST['time']=="") {
$timeErr = "Please select the reservation time";
} else {
$time = test_input($_POST["time"]);
}
if($nameErr == "" && $teleErr == "" && $emailErr == "" && $partyErr == "" && $vipErr == "" && $reservationErr == "" && $timeErr == ""){
header('Location: http://yoursite.com/dashboard');
exit();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
You can redirect your user using the header().
header('Location: http://yoursite.com/dashboard');
exit();
Where are you sending this form data to?. To itself or database. Anyway upon submission, you can echo
any of this javascript function to
redirect the user to a new page after 1 seconds.
echo "<script>
window.setTimeout(function() {
window.location.href = 'redirect.php';
}, 1000);
</script>";
or
echo '<script>
$(document).ready(function() {
window.setInterval(function() {
var timeLeft = $("#timeLeft").html();
if(eval(timeLeft) == 0){
window.location= ("welcome.php");
}else{
$("#timeLeft").html(eval(timeLeft)- eval(1));
}
}, 1000);
});
</script>';
Try this
<?php
$nameErr = $teleErr = $emailErr = $partyErr = $vipErr = $reservationErr = $timeErr = "";
$name = $tele = $email = $party = $vip = $reservation = $time = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$c = 0;
if(empty($_POST["name"])) { {
$nameErr = "Please enter a full name";
$c++;
}
if(!empty($_POST["name"])) {
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Invalid name entered";
$c++;
}
}
if (empty($_POST["tele"])) {
$teleErr = "Please enter a telephone number";
$c++;
}
if (!empty($_POST["tele"])) {
$tele = test_input($_POST["tele"]);
if (!preg_match("/^[0-9 ]{7,}$/",$tele)) {
$teleErr = "Invalid telephone number entered";
$c++;
}
}
if (empty($_POST["email"])) {
$emailErr = "Please enter an email address";
$c++;
}
if (!empty($_POST["email"])) {
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email entered";
$c++;
}
}
if($_POST['party']=="") {
$partyErr = "Please select the party size";
$c++;
} else {
$party = test_input($_POST["party"]);
}
if (empty($_POST["vip"])) {
$vipErr = "Please make a VIP area selection";
$c++;
} else {
$vip = test_input($_POST["vip"]);
}
if (empty($_POST["reservation"])) {
$reservationErr = "Please enter the reservation date";
$c++;
}
if (!empty($_POST["reservation"])) {
$reservation = test_input($_POST["reservation"]);
if (!preg_match("/^[0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}$/",$reservation)) {
$reservationErr = "Invalid reservation date";
$c++;
}
}
if($_POST['time']=="") {
$timeErr = "Please select the reservation time";
$c++;
} else {
$time = test_input($_POST["time"]);
}
if($c == 0) {
// redirect here
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Indeed you have done a lot of complication without using Arrays. You may in the case of an error existence set an array named $errors and its key should be the element of the form which is being on check. For example look at the following blue print code:
if (!my_check_email($_POST['email'])){
/* my_check_email() is a custom function the performs email validation. It returns true for valid email and it returns false for invalid email
*/
// Here invalid email
$errors['email'] = true;
}
The repeat similar coding style for other elements of the form you want to validate. At the end you just have to check if the $errors is set or not as follows:
if (isset($errors)){
// do the necessary code for invalid input
}
else{
// Save the data and redirect the user using any mean of redirection.
}
Means of redirection
1- using php header function as other answers stated. However, using header function should be used before any output in your file i.e before any echo or print or even any new line or html tags in your script file.
2- using cient-side javascript like the follwoing:
echo "<script>\n
window.location.href = 'redirect.php';\n
</script>";
3- Using client-side meta tag:
echo '<meta http-equiv="refresh" content="0;URL=http://www.indiana.edu/~account/new-directory" />';

Not displaying Error Message

i am a newbie in this php. i am trying to make some validation for my form which will show the error msg if it exploits my validation rules.
my connection file.
<?php
$con = mysql_connect("localhost","root","") or die('could not connect the server: '. mysql_error());
mysql_select_db("interview",$con);
?>
my validate.php file
<?php
require_once('connect.php');
$realnameErr = $nickErr = $passwordErr = $emailErr = "";
$realname = $nick = $password = $email = "";
?>
my form
<form name='v2' id='login' method='post' action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<legend>Login</legend>
<label for='realname' >Real Name*:</label>
<input type='text' name='realname' id='realname' maxlength="50" value="<?php echo $realname;?>" /></br>
<span class="error"><?php echo $realnameErr;?></span>
<br>
<label for='nick' >Nick*:</label>
<input type='text' name='nick' id='nick' maxlength="50" value="<?php echo $nick;?>" /></br>
<span class="error"><?php echo $nickErr;?></span>
<br>
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" /></br>
<span class="error"><?php echo $passwordErr;?></span>
<br>
<label for='email' >Email*:</label>
<input type='text' name='email' id='email' maxlength="50" value="<?php echo $email;?>"/></br>
</fieldset>
<input type='submit' name='submit' value='submit' />
</form>
validation begins here
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_POST['submit'])) {
if (empty($_POST["realname"]))
{
$realnameErr = "Name is required";
}
else
{
$realname=test_input($_POST["realname"]);
if(!preg_match("/^[a-zA-z ]*$/",$realname))
{
$realnameErr = "only letters and white space allowed";
}}
if(empty($_POST["nick"]))
{
$nickErr = "Nick is required";
}
else {
$nick=($_POST["nick"]);
}
if(empty($_POST["password"]))
{
$passwordErr = "password is required";
}
else {
$password=($_POST["password"]);
}
if(empty($_POST["email"]))
{
$emailErr = "email is required";
}
else {
$email=test_input($_POST["email"]);
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailErr = "Invalid email format";
}}
checking then inserting
if((!$realnameErr) && (!$nickErr) && (!$passwordErr) && (!$emailErr)) {
$query="INSERT INTO `main`"."(realname,nick,password,email)". "VALUES". "('$realname','$nick',SHA('$password'),'$email')";
$res=mysql_query($query);
echo '<p>Your account has been Successfully created,You are now ready to login. </p>';
}
}}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
You need to have your working Script before you display your form. Because at the moment, the time you output <span class="error"><?php echo $nickErr;?></span> the variable $nickErr is still empty and therefore does not display anything.
Try this:
// Init
$errors = array();
// Validate Post Data
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['submit'])) {
if (empty($_POST["realname"])) {
$errors[] = "Name is required";
} else {
$realname = test_input($_POST["realname"]);
if (!preg_match("/^[a-zA-z ]*$/", $realname)) {
$errors[] = "only letters and white space allowed";
}
}
if (empty($_POST["nick"])) {
$errors[] = "Nick is required";
} else {
$nick = ($_POST["nick"]);
}
if (empty($_POST["password"])) {
$errors[] = "password is required";
} else {
$password = ($_POST["password"]);
}
if (empty($_POST["email"])) {
$errors[] = "email is required";
} else {
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$errors[] = "Invalid email format";
}
}
}
}
// If there is any error
if (sizeof($errors))
{
// display it
echo '<div>Following error(s) occured:<br /><br />'. implode('<br />', $errors) .'</div>';
}
else
{
// proceed with db insert here
}

Categories