I am trying to validate a form using php, the code i have doesn't prevent the form from being submitted when the inputs are invalid, however, the error messages that i would like them displayed do not show on the form, the form is returned empty of error messages even tho i have them echo'ed inside the form. could you help me display the error messages upon unsuccessful submission of the form ? i added my form code and the php code. both are seperate files , the action in the form leads to the php validation code like so (action = "report_form_php.php).
<form method="post" onsubmit=" return formSubmit()" action="report_form_php.php">
<div class="error1" id= "errorMsg">* Required Fields</div>
<div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com" >
</div><br>
<div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";
// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staffname"])) {
$staffErr = "Staff Name is required";
} else {
$staff_name = test_input($_POST["staffname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
$staffErr = "Only letters and white space allowed";
}
}
// email validation:
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 = "Please enter a valid email.";
}
}
// subject validation:
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
// check if subject only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
$subjectErr = "Only letters and white space allowed";
}
}
// problem type validation:
if (empty($_POST["problem_type"])) {
$problemErr = "Problem type is required";
} else {
$problem_type = test_input($_POST["problem_type"]);
}
// description validation:
if (empty($_POST["description"])) {
$descriptionErr = "A Description is required";
} else {
$description = test_input($_POST["description"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($staffErr == "" && $emailErr == "" &&$subjectErr == "" &&$problemErr == "" &&$descriptionErr == "") {
header("Location: insert_logs.php");
exit();
} else {
header("Location: log-it-reportsbeta.php");
exit();
}
?>
This basic php codes below should give you the ideas for 3 states of a form submission process to adjust your code properly.
success
system failure (bug or a temp. server issue for example)
invalid user data input
// data were valid && script's aim is achieved
if (isset($_SESSION['state']) && $_SESSION['state'] == 1) {
// your thanks/result page's content here;
echo 'Thanks. Transaction was successful.';
unset($_SESSION['state']);
return; // not to continue
}
// form not submitted yet
if ( false === (isset($_POST['submit']) && $_POST['submit'] = "your val")) {
require 'form.php';
return; // not to continue
}
// form submitted
require 'validate.php'; // PHP codes to validate data from POST global var.
// data are valid
if (valid($_POST)) {
// try what you aim with valid data
require 'perform_aim.php';
if (perform_aim_successful()) { // for example: record was inserted
$_SESSION['state'] = 1; // success state
header("Location: YOUR URL", TRUE, 301); // prevents reprocessing by F5 ($_POST is empty again by 301.)
exit; // exit after a redirect
}
else {
echo 'Your data was OK but script was failed. Try again later';
}
}
// invalid data
else {
print_r($err_msgs); // error messages from/by 'validate.php'
require 'form.php';
}
Related
I have to verify and validate information inputted in an HTML form against a database created in phpMyAdmin. Currently, when I input my data and hit submit, I get a message that I have at the end of my PHP file. (Account not found). Also whatever transaction they select should be redirected to that page.
Is it giving me an error msg because I have the wrong name somewhere or is it skipping over all the functions?
This is the Form
<body>
<form name="form" action="Verify.php" method="post">
<h1>Lushest Lawns and Landscaping</h1>
<label for="input"><b>Landscaper's First Name: </b></label>
<input type="text" name="fname" placeholder="Example: John" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Last Name: </b></label>
<input type="text" name="lname" placeholder="Example: Doe" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Password: </b></label>
<input type="password" name="pass" placeholder="Example: Ba9877bb$Bb9" required >
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's ID#: </b></label>
<input type="number" name="id" placeholder="Example: 123456" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Phone#: </b></label>
<input type="number" name="Pid" placeholder="Example: 1234567890" required>
<label for="required"><b>REQUIRED</b></label>
<br>
<label for="input"><b>Landscaper's Email: </b></label>
<input type="text" name="email" placeholder="Example: abc#abc.com">
<br>
<label for="input"><br><b>Select a Transaction: </b></label>
<select id="transaction" name="transaction" required>
<option name="1">Search A Landscaper's Accounts</option>
<option name="2">Book A Customer's Appoinment</option>
<option name="3">Place A Customer's Order</option>
<option name="4">Update A Customer's Order</option>
<option name="5">Cancel A Customer's Appoinment</option>
<option name="6">Cancel A Customer's Order</option>
<option name="7">Create A New Customer Account</option>
</select>
<br>
<input type="checkbox" id="confirmation" name="emailconfirm">
<label for="checkbox"><b>Email the Transaction Confirmation</b></label>
<button class="button button5" name="submit">Submit</button>
</form>
</body>
This is the PHP file. I just removed the server name and everything for now but I have it in my file.
<?php
if(isset($_POST["submit"])){
session_start();
$servername = "";
$username = "";
$password = "";
$dbname = "";
$connection = mysqli_connect($server,$username,$password,$dbname);
if($connection-> connect_error){
die("Connection failed: " . $connection-> connect_error);
}
//Form input data
$Fname = $_POST["fname"];
$Lname = $_POST["lname"];
$Lid = $_POST["id"];
$Lpass = $_POST["pass"];
$transaction = $_POST["transaction"];
$Lemail = $_POST["email"];
$Lphone = $_POST["Pid"];
$_SESSION['id'] = $Lid;
$validate = true;
$verify = false;
function validate() {
//validate first name
if (empty($_POST["fname"])) {
echo ("First Name is required <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate last name
if (empty($_POST["lname"])) {
echo ("Last Name is required <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate id
if (empty($_POST["id"])) {
echo("Invalid ID: Enter 6-digit number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate password
if (empty($_POST["pass"])) {
echo("Invalid Password: Enter 6-digit number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//Validate transaction
if (empty($_POST["transaction"])) {
echo ("Please select a Transaction <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//Validate phone number
if (empty($_POST["Pid"])) {
echo("Invalid Phone Number <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
//validate email
if(isset($_POST["emailconfirmation"]) && !empty($_POST["emailconfirmation"])) {
if(empty($_POST["emailconfirmation"])) {
echo("Please enter an Email <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
} else {
$email = $_POST["emailconfirmation"];
if (!filter_var($email, 'FILTER_VALIDATE_EMAIL')) {
echo ("Invalid Email Format, Correct Format: email#example.com <br>");
$validate = false;
header( "refresh:3;url=Pro4.html" );
}
}
}
}
function verify($connection) {
$sql = "SELECT * FROM `Landscaper DB`";
$result = $connection -> query($sql);
while ($row = $result-> fetch_assoc()) {
if (($_POST["fname"]) == ($row["LFirstName"])) {
if (($_POST["lname"]) == ($row["LLastName"])) {
if ($_POST["id"] == $row["LID"]) {
if ($_POST["Pid"] == $row["LPhone"]) {
if ($_POST["pass"] == $row["LPassword"]){
return true;
}
}
}
}
}
}
return false;
}
validate();
if(validate()) {
$verify = verify($connection);
}
if($verify) {
//transaction
if($transaction == "1") {
header("Location: Landscaper.php" );
}
elseif($transaction == "2") {
header("Location: AppoinmentForm.html" );
}
elseif($transaction == "3") {
header("Location: OrderForm.html");
}
elseif($transaction == "4"){
header("Location: UpDateOrder.html" );
}
elseif($transaction == "7"){
header("Location: CreateAccount.html" );
}
elseif($transaction == "5"){
header("Location: CancelCusApoin.html" );
}
elseif($transaction == "6"){
header("Location: CancelOrder.html" );
}
}
else {
echo "Sorry, account not found.\n Please try again with a valid Name, ID, and Password.";
header( "refresh:3;url=Pro4.html" );
}
$connection -> close();
}
?>
DATABASE
This is the table of inputs that should work.
You're not going to pass validation because your select element options have no values, so transaction will be blank.
You have lots of badly formed html. Read up on forms, labels, input elements, and IDs, names, and values. Once you have the html ironed out then the server side validation will follow.
validate();
if(validate()) {
$verify = verify($connection);
}
For whatever reason you are calling the validate() function twice. You only need to call it once. Additionally, you are checking the return value of the validate() function with an if() statement, but your validate() function does not have any return statement. This means that the "return value" of this function is always NULL. This will result in the following code/execution:
validate();
if(NULL) {
$verify = verify($connection);
}
That way the if() block is never executed. So your verify() function is never called and your $verify variable is never updated, it stays false. When you want to use your verify() function in an if() statement, your function has to use the return statement to return a "result" like return true; or return false;.
Your $_POST['transaction'] field does not contain the name="..." values but instead the label content of the <option> entry. The syntax to set a (different) value for an <option> entry is set the value="..." attribute, something like:
<option value="4">Update A Customer's Order</option>
You can always check with var_dump($_POST); to see what the actual values are the browser is sending to your PHP script.
I would like to validate a form on the server before submitting it to a database, i managed to write a php code that shows error messages for invalid inputs once the user clicks submit in the form, which is step one, however, step two is to prevent the form from submitting which is what i would like to know how , because despite error messages showing that input was invalid, the input goes to the data base. i tried to define a "$valid = true" variable , and then return it as false after each error message, but it didnt help ..
<?php
// define variables and set to empty values
$staffErr = $emailErr = $subjectErr = $problemErr = $descriptionErr= "";
$staffname = $email = $subject = $problem_type = $description = "";
$valid = true;
// staff name validation:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["staffname"])) {
$staffErr = "Staff Name is required";
$valid = false;
} else {
$staff_name = test_input($_POST["staffname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$staffname)) {
$staffErr = "Only letters and white space allowed";
$valid = false;
}
}
// email validation:
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 = "Please enter a valid email.";
}
}
// subject validation:
if (empty($_POST["subject"])) {
$subjectErr = "Subject is required";
} else {
$subject = test_input($_POST["subject"]);
// check if subject only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$subject)) {
$nameErr = "Only letters and white space allowed";
}
}
// problem type validation:
if (empty($_POST["problem_type"])) {
$problemErr = "Problem type is required";
} else {
$problem_type = test_input($_POST["problem_type"]);
}
// description validation:
if (empty($_POST["description"])) {
$descriptionErr = "A Description is required";
} else {
$description = test_input($_POST["description"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" onsubmit=" return formSubmit()" action="#">
<div class="error1" id= "errorMsg">* Required Fields</div>
<div class="error" id= "errorMsg1">*<?php echo $staffErr; ?></div>
<div>
<label for="staff_name"><b>Staff Name:</b></label>
<input class="field" id="staff_name" name="staffname" onclick=" return staffValidation()" onchange=" return staffValidation()" id="subject" type="text" placeholder="Staff Name" >
</div><br>
<div class="error" id= "errorMsg2">*<?php echo $emailErr; ?></div>
<div>
<label for="email"><b>Email:</b></label>
<input class="field" id="email1" name="email" onclick=" return emailValidation()" onchange=" return emailValidation()" type="email" placeholder="staff#wearview.com" >
</div><br>
<div class="error" id= "errorMsg3">*<?php echo $subjectErr; ?></div>
<div>
<label for="subject"><b>Subject:</b></label>
<input class="field" name="subject" id="subject1" onclick=" return subjectValidation()" onchange=" return subjectValidation()" type="text" placeholder="Subject Title" >
</div><br>
<div class="error" id= "errorMsg4">*<?php echo $problemErr; ?></div>
<div>
<select onclick=" return problemValidation()" onchange=" return problemValidation()" class="field4" name="problem_type" id="problemtypes">
<option value="">Problem Type</option>
<option value="Hardware">Hardware</option>
<option value="Software">Software</option>
<option value="Software&Hardware">Software & Hardware</option>
<option value="Other">Other</option>
</select>
</div><br>
<div class="error" id= "errorMsg5">*<?php echo $descriptionErr; ?></div>
<div>
<textarea class="field2" id="description1" name="description" onclick=" return descriptionValidation()" onchange=" return descriptionValidation()" placeholder="Description goes here" rows="15" cols="90"></textarea>
</div>
<div>
<button class="field3" type="submit" class="btn">Submit</button>
<input type="checkbox" id="notify" name="notify" value="">
<label for="notify">Inform me by email when issue is resolved.</label>
</div>
</form>
Here's an example (all PHP) without Javascript but with better security & email check. Tested on a working server. If you want an example with a properly protected insert statement, let me know and I'll add to this answer.
<?php
$name = $response_name = $email = $response_email = ""; // Clear variables
// Name (trims white space and doesn't accept names under 2 characters or over 20 characters)
if (isset($_POST['myform'])) {
$name = mysqli_real_escape_string($con, $_POST['name']);
if (empty($name) || strlen(trim($name)) < 2 || strlen(trim($name)) > 20) {
$response_name = "bad name";
}
// Email (checks for correct email format and tests a response from the email domain server example: gmail.com)
$email = mysqli_real_escape_string($con, $_POST['email']);
$email_host = strtolower(substr(strrchr($email, "#"), 1));
$email_host = idn_to_ascii($email_host.'.');
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false || !checkdnsrr($email_host, "MX")) {
$response_email = "bad email";
}
if ($response_name=="" && $response_email=="") {
echo "data ok, proceed";
// Now send to MySQL table...
}
}
echo "
<form method='post'>
<label for='name'><b>Name:</b> $response_name</label>
<input name='name' type='text' value='$name' placeholder='Enter your name'>
<label for='email'><b>Email:</b> $response_email</label>
<input name='email' type='email' value='$email' placeholder='Enter your email' >
<button type='submit' name='myform'>SUBMIT</button>
</form>
";
?>
Note: For forms, Javascript is good for initial data error detection but to be really secure you would want to check with PHP and so if you're already using Javascript for forms you should be using AJAX as it's much more user friendly (no page reloading required) and you'll be able to reference an external PHP file which keeps code neater and tidier, at least IMO!
my code does work properly I am just having trouble with removing "Please enter your name" and only displaying the welcome message after the user submits their name.
I've tried to use conditional statements that just led to an error
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}//$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$method = $_SERVER["REQUEST_METHOD"];
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = isset($_POST["name"])? $_POST["name"]: "";
validate_name($name, $err);
}
?>
<!-- The form -->
<form method="post">
<center><label>
<input type="text" name="name" value="<?php echo #$name;?>">
</label></center>
<!-- Show if no error -->
<?php if(empty($err)) { ?>
<span><p class="centered-text">Please enter your name</span>
<?php } else { ?>
<!-- Show if error -->
<span class="error">
<?php echo $err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php if(isset($name) && empty($err)){ ?>
<p class=" centered-text">Hi <?php echo $name?>!</p>
<p class="centered-text">Welcome to our store!</p>
<?php } ?>
My expected result is to display "please enter your name" and once the user submits to remove the instruction "please enter your name" and display the welcome message only
<?php
# filter input
function filter($var) {
return htmlspecialchars(stripslashes(trim($var)));
}
# validate name
function validate_name(&$name, &$err){
if(empty($name)){
$err = "Name is required";
return;
}
$name = filter($name);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$err = "Only letters and white space allowed";
}
}//$method = filter_input(INPUT_SERVER, 'REQUEST_METHOD');
$method = $_SERVER["REQUEST_METHOD"];
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = isset($_POST["name"])? $_POST["name"]: "";
validate_name($name, $err);
}
if(isset($name) && empty($err)){ ?>
<p class=" centered-text">Hi <?php echo $name?>!</p>
<p class="centered-text">Welcome to our store!</p>
<?php } else { ?>
<!-- The form -->
<form method="post">
<center><label>
<input type="text" name="name" value="<?php echo #$name;?>">
</label></center>
<!-- Show if no error -->
<?php if(empty($err)) { ?>
<span><p class="centered-text">Please enter your name</span>
<?php } else { ?>
<!-- Show if error -->
<span class="error">
<?php echo $err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php } ?>
The error check should only be done if $name is set. If it's not set, the form hasn't been submitted and you should only show the "Please enter your name" message in that case.
Here's the basic logic (HTML not included to improve clarity):
if (!isset($name)) {
// Name has not been submitted yet, show "Please enter your name" message
else {
if (empty($err)) {
// Name was submitted and validated successfully, show welcome message
} else {
// Name was submitted with errors, show the errors
}
}
I have a simple PHP page, and am attempting to validate form input.
Upon hitting submit with invalid data, the inputted value is not being returned in my echo statement
I want to echo the input as the value so that the user can understand what they typed wrong. Below is my code;
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
<?php
// define variables and set to empty values
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<!--Begin HTML Form-->
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr;?></span><br> <!--<p class='spacerLine'></p>-->
<input type="text" class="largeInput" name="contactFirstName" value="<?php echo $contactFirstName;?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php echo $contactEmail;?>">
<br><br>
<?php echo "TEST" . $contactEmail;?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php echo $retailerID;?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Any thoughts? I'm new to PHP but have been following the W3 tutorial pretty tightly. Could it be my classes throwing things off? Or did I just mess up a variable name?
Thanks for all help
I want to echo the input as the value so that the user can understand what they typed wrong.
Neither the echo of "TEST" . $contactEmail nor the input value are displaying $contactEmail
First of all, echo $_POST values instead of $contactFirstName, $contactEmail etc. because these values are available only after it crosses all the validation steps.
Second, there's no function named test_input() in your code, or may be it is defined somewhere else.
And finally, look at this statement here:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { ..
There's no variable named $email in your code. It should be:
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) { ..
So your code should be like this:
<?php
function test_input($string){
// your code
}
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = test_input($_POST["contactFirstName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (!filter_var($_POST["contactEmail"], FILTER_VALIDATE_EMAIL)) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = test_input($_POST["contactEmail"]);
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = test_input($_POST["retailerID"]);
}
}
?>
<div class="Form_container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Contact First Name<span class="required">*</span><span class="formError"><?php echo $contactFirstNameErr; ?></span><br>
<input type="text" class="largeInput" name="contactFirstName" value="<?php if(isset($_POST['contactFirstName'])){ echo $_POST['contactFirstName']; } ?>">
<br><br>
Contact E-mail<span class="required">*</span><span class="formError"> <?php echo $contactEmailErr;?></span><br>
<input type="text" class="largeInput" name="contactEmail" value="<?php if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; } ?>">
<br><br>
<?php
echo "TEST ";
if(isset($_POST['contactEmail'])){ echo $_POST['contactEmail']; }
?>
<br><br>
Retailer<span class="required">*</span><span class="formError"><?php echo $retailerIDErr;?></span><br>
<input type="text" class="largeInput" name="retailerID" value="<?php if(isset($_POST['retailerID'])){ echo $_POST['retailerID']; } ?>">
<br><br>
<input type="submit" class="button" name="submit" value="Add Contact">
</form>
</div>
Here's the reference for isset() function:
isset()
Sidenote: Even though this answer will work you temporarily, but you should definitely look at how to strictly validate form inputs using regex.
The below line validates the value of the variable $email, but i can't see anywhere in your code where does that variable get set a value, that can be the first step in fixing the issue.
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
You are not defining test_input() function and $email is not defined in this line:
if (!filter_var($email, FILTER_VALIDATE_EMAIL))
This code works for me so far:
$contactFirstNameErr = $contactEmailErr = $retailerIDErr = "";
$contactFirstName = $contactEmail = $retailerID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input fields
if (empty($_POST["contactFirstName"])) {
$contactFirstNameErr = "<br>*First Name is required";
} else {
$contactFirstName = $_POST["contactFirstName"];
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$contactFirstName)) {
$contactFirstNameErr = "<br>*Only letters and white space allowed";
}
}
//Email Field
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Email is required";
} else {
// check if e-mail address is well-formed
if (empty($_POST["contactEmail"])) {
$contactEmailErr = "<br>*Invalid email format";
} else {
$contactEmail = $_POST["contactEmail"];
}
}
//Option Field
if (empty($_POST["retailerID"])) {
$retailerIDErr = "<br>*Retailer is required";
} else {
$retailerID = $_POST["retailerID"];
}
}
In this program when i am clicking submit button the page directly goes on other page 2222.php. The error message not pop up.. I just want hit error message when clicking on submit button...
php_validation.php
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$name = $email = $gender ="";
// On submitting form below function will execute.
if(isset($_POST['submit']))
{
if (empty($_POST["name"])) //---------------------------------------------- -------------------------
{
$nameError = "Name is required";
}
else
{
$name = test_input($_POST["name"]);
// check name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name))
{
$nameError = "Only letters and white space allowed";
}
//-----------------------------------------------------------------------
}
if (empty($_POST["email"])) //---------------------------------------------- -------------------------
{
$emailError = "Email is required";
}
else
{
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid or not
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email))
{
$emailError = "Invalid email format";
}
}
//-----------------------------------------------------------------------
if (empty($_POST["gender"]))
{
$genderError = "Gender is required";
}
else
{
$gender = test_input($_POST["gender"]);
}
}
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" name="myForm" action="2222.php">
<p>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError;?></span>
</p>
<br><br>
<p>
Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError;?></span>
</p>
<br><br>
<p>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">*<?php echo $genderError;?></span><br><br />
</p>
<input class="submit" type="submit" name="submit" value="Submit" >
</form>
</body>
2222.php
<?php
$name = $_POST['fname'];
$email = $_POST['email'];
$radio = $_POST['gender'];
echo "<h2>Your Input:</h2>";
echo "user name is: ".$name;
echo "<br>";
echo "user email is: ".$email;
echo "<br>";
echo "user is ".$radio;
?>
So I've done a quick code for you :
Here is your "php_validation.php" :
<?php
//Init error var
$nameError = '';
$emailError = '';
$genderError = '';
//Did we have an error ?
if(isset($_GET['error'])){
//Split error return into an array
$errorList = explode('_', $_GET['error']);
//Verify every possible error
if(in_array('name',$errorList)){
$nameError = 'Please enter your name<br>';
}
if(in_array('email',$errorList)){
$emailError = 'Please enter your email<br>';
}
if(in_array('gender',$errorList)){
$genderError = 'Please enter your gender';
}
}
?>
I didnt changed the form
Then this is your "2222.php" :
<?php
$error ='';
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//When we receive data
if(isset($_POST)){
//Verify all possible data and set error
if(!empty($_POST['fname'])){
$name = test_input($_POST['fname']);
}else{
$error .= 'name_';
}
if(!empty($_POST['email'])){
$email = test_input($_POST['email']);
}else{
$error .= 'email_';
}
if(!empty($_POST['gender'])){
$radio = test_input($_POST['gender']);
}else{
$error .= 'gender_';
}
//if we have an error then redirect to form with error
if(!empty($error)){
header("Location:php_validation.php?error=".$error);
}
}
?>
Didnt changed your output on this page either.
So as I said previously when you here is what happend when you click the submit button :
Submit Click
Form sent to 2222.php as $_POST and you're redirected to this page
There is no way that could be working if your form is posting on an other page than the one where the check is made.
Since your form's action is "2222.php", on click the submit button will automatically redirect you to 2222.php before doing anything.
If you want to check what you've received by your form, you can do it in your "2222.php", then redirect it with the error message to php_validation.php
You could do one of the following things:
Do all the checking in Javascript "onClick" function
Do Ajax call "onClick" to a handler page, get the validation message from that page.
Do the validation on "2222.php" page
action back to the same page (since you are doing some validation here) and redirect after validation on "2222.php" page
Now depends only on you which fits your program.
If you want to stay on the same page you could submit the form to an iframe, as the results of the processing script would be displayed in the iframe itself.
Example:
files:
file-with-form.php
form-submit-processing-file.php
Code examples:
file-with-form.php
<!DOCTYPE html>
<html>
<head>
<title>[Your page title]</title>
</head>
<body>
<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<!-- Form -->
<form action="[path-to-form-submit-process]" method="[GET|POST]"
target="form-processor">
<div>
<label>First Name:
<input type="text" name="fname" id="fname" />
<span class="error">* <?php echo $nameError ?></span>
</label>
</div>
<div>
<label>Email:
<input type="text" name="email" id="email">
<span class="error">* <?php echo $emailError ?></span>
</label>
</div>
<div>
<label>Gender:
<p><input type="radio" name="gender" value="female"> Female</p>
<p><input type="radio" name="gender" value="male"> Male</p>
<p><span class="error">*<?php echo $genderError ?></span></p>
</label>
<input class="submit" type="submit" name="submit" value="Submit" >
</div>
</form>
<!-- The iframe to submit the form to -->
<iframe name="form-processor" id="form-processor"
src="[path-to-form-submit-process]"></iframe>
<!--
NOTE: The error message spans are left there just because you had them
in your code, those will not work here at this point, actually depending
on your php configuration will most probably throw errors/warnings,
because such variables were not defined at all...
-->
</body>
</html>
As:
[path-to-form-submit-process] - a placeholder to be replaced with the URL to the file/ Controller -> Action that would process the passed form data
[*] - placeholders that should be replaced with the values for your case
form-submit-processing-file.php
<?php
# Processing the form fields and displaying the messages
$post = $_POST;
# Preprocessing the passed data
// Here you would filter out data from the $_POST superglobal variable
# Validating the passed data
// Check if the data entries, e.g.
// Flag for error risen - does not let the process to be completed
$invalidFormData = false;
$messages = [];
function addErrorMessage($message, &$messages, &$errorFlag)
{
$errorFlag = true;
$errorMessageTemplate = '<p class="error-message">{message}</p>';
array_push($messages, str_replace('{message}', $message,
$errorMessageTemplate));
}
// Validating the email
$email = array_key_exists('email', $post)
? $post['email']
: null;
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
// Raising the flag for an error on validation
addErrorMessage("$email is not a valid email address", $messages, $invalidFormData);
}
// ........
// validation of rest of fields
// ........
$internalError = false;
# Some business logic after the validation, recording more messages etc.
try {
// ........
} catch (Exception $e) {
$internalError = true;
}
# Stop execution on internal error
if ($internalError === true)
{
?>
<h2>Sorry, there's an error on our side... we'll do all in our
powers to fix it right away!</h2>
<?php
exit;
}
# Displaying the results
if ($invalidFormData === true) {
// Building errors message
$messagesHeading = '<h2>There were problems submitting your data. :/</h2>';
} else {
$messagesHeading = '<h2>Your data was successfully submitted! Yay!</h2>';
}
// Placing the heading in front of other messages
array_unshift($messages, $messagesHeading);
// Displaying the messages:
echo implode('', $messages);
However I believe this should be done via an AJAX call insted.
Also there are a lot of bad practices in this case, so I would suggest checking out some design patterns and architectures as MVC for instance and consider using a framework like Symfony/Laravel/CodeIgniter... There are a lot of tools that will make your life easier :)