Failure message doesn't display when invalid PHP form is submitted - php

I'm having some difficulty with a PHP form, the problem being that my confirmation message displays even when the form fields have not been validated.
If the form has not been validated, I would like to display an alternative message that explains to the user that something went wrong and their message was not sent.
Unfortunately, my understanding of PHP is only as good as the tutorials I've taken in trying to put this form together so I'm a bit stuck! Would someone be kind enough to explain to me what I am doing wrong?
Here's the code:
<?php
ini_set('display_errors', 'On');
//Defines error variables and sets to empty
$senderErr = $senderEmailErr = $messageErr = "";
//Defines text entry variables and sets to empty
$sender = $senderEmail = $message = "";
//Defines failure/confirmation messages and sets to empty
$thankYou = "";
$formFail = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["sender"])) {
$senderErr = "Name is required";
} else {
$sender = test_input($_POST["sender"]);
// Checks that name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$sender)) {
$senderErr = "Only letters and white space allowed";
}
}
if (empty($_POST["senderEmail"])) {
$senderEmailErr = "Email is required";
} else {
$senderEmail = test_input($_POST["senderEmail"]);
// Checks if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$senderEmail)) {
$senderEmailErr = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$messageErr = "You haven't written anything";
} else {
$message = test_input($_POST["message"]);
}
if($_POST["submit"]) {
$recipient="me#email.com";
$subject="enquiry";
$sender=$_POST["sender"];
$senderEmail=$_POST["senderEmail"];
$message=$_POST["message"];
$mailBody="Name: $sender\nEmail: $senderEmail\n\n$message";
mail($recipient, $subject, $mailBody, "From: $sender <$senderEmail>");
$thankYou = "Thanks for your message. We'll get back to you shortly";
}
else {
$formFail = "Oops. Something went wrong. Please fill out the required fields.";
}
}
?>
I think it has something to do with the fact that I'm not setting the right conditions for failure. Problem is, I'm not quite sure where to start. Apologies for being a noob. Help appreciated. Thanks.
Edit - here's the HTML in response to Fred's question about whether the elements are named:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Name:</label></br>
<input type="text" name="sender"></br>
<span class="error">* <?php echo $senderErr;?></span>
</br>
<label>Email address:</label></br>
<input type="text" name="senderEmail"></br>
<span class="error">* <?php echo $senderEmailErr;?></span>
</br>
<label>Message:</label></br>
<textarea rows="5" cols="20" name="message"></textarea></br>
<span class="error">* <?php echo $messageErr;?></span>
<input type="submit" name="submit" value="submit"></br>
</form>
<span><?php echo $thankYou;?></span>
<span><?php echo $formFail;?></span>

Replacing if($_POST["submit"]) with if(($_POST["submit"]) && !empty($_POST["sender"]) && !empty($_POST["senderEmail"]) && !empty($_POST["message"])) will fix the problem.
Using PHP's empty() function, ensures that if something is left "empty" and used in a conditional statement, will not execute until all conditions are met.
All being the && (logical) operator.

Related

prevent going to confirmation page if entries are not correct

I am doing this to learn, got it from examples here and there and, following an online tutorial. What I have not been able to do so far is to prevent it to go to the confirmation.php page if one of the entry is either empty, has numbers (name and lastname) or the email adress is invalid.
If i use action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" I see when thre is an error in the fields but, when action is set to confirmation.php, even if there is an error, it will go with the entered data.
Just for info of my next step, confirmation.php would be a page displaying the info entered with a submit button (to a DB) or an update button if the user made a mistake so he can fix it before sending to db.
Just so you know, I am just starting paying with php so, please, I would appreciate if your answer was not to generic :-)
Thank you
<?php
// define variables and set to empty values
$nameErr = $lastNameErr = $emailErr = "";
$name = $lastName = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])||(ctype_space($_POST["name"]))) {
$nameErr = "Prénom Requis";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Lettre seulement";
}
}
if (empty($_POST["lastName"])||(ctype_space($_POST["lastName"]))) {
$lastNameErr = "Nom Requis";
} else {
$lastName = test_input($_POST["lastName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$lastName)) {
$lastNameErr = "Lettre seulement";
}
}
if (empty($_POST["email"])||(ctype_space($_POST["email"]))) {
$emailErr = "Adresse courriel requise";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Adresse courriel non valide";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Inscription du participant</h2>
<p><span class="error">* Champ requis.</span></p>
<form method="post" "confirmation.php">
Prénom: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Nom: <input type="text" name="lastName" value="<?php echo $lastName;?>">
<span class="error">* <?php echo $lastNameErr;?></span>
<br><br>
Courriel: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You can easily achieve what you want just by adding the "required" attribute to your input field html element.
Have a look here: https://www.w3schools.com/tags/att_input_required.asp
By adding "required" the browser itself will prevent the form to be sent.
Furthermore, for the "email" input, try to change its type to email (type="email" which will also add the default browser validation for an email address.
Have a look here for more default validation in form input fields: https://www.w3schools.com/htmL/html_form_input_types.asp
You are missing action= inside your <form>. It just says confirmation.php

PHP script allowing empty (blank) fields to database

EDIT: Code modified to include $errors variable. Please let me know if this will work, thanks.
I am new to PHP and MySQL. I have the below php code inside my web form and I am having a problem with it inserting a new record into the database when any of the web fields are blank or improperly formatted.
I have error checking occuring that will display an error message in red after pressing Submit button AND data is either blank or improperly formatted. This part is working fine, the problem is that it still allows the record to post to the database when there are blank/improperly formatted values. I would like to add some scripting to check to see if any of the mandatory fields are blank or formatted improperly and if so, do not proceed with the SQL Insert. I would appreciate if someone can help me with what scripting I should add. Below is the code I am using, thanks!
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
<?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";
$errors = "true";
}
}
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'])) {
and $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>
Try using the validated field values in your SQL statement, rather than using the $_POST variables again - and if the field doesn't exist, don't run the query.
Alternatively, don't run the SQL statement if any errors were found at the beginning of the script. To achieve this, I would do:
set a variable $errors to false at the start of the script
whenever any error is found, set the $errors variable to true
at the end of the script, where you have if (isset($_POST['submitted'])), also check that $errors is false before you actually run the insert.
Hope that helps.
In the above code your not checking for invalid data before inserting. Your just checking for the errors and bypassing it and storing in db. So modified the if condition as below.
if (isset($_POST['submitted']) && empty($err_array))
In $err_array store the error values instead of individual variables.
I separated out your php from your html for clarity. First and most important, as was pointed out above you are vulnerable to SQL Injection attacks please use tokenized parameters and prepared statements to help protect yourself from this issue (example below).
On to your question, I would suggest trying to add some exception handling to your workflow. This might seem a bit intimidating if you are just starting out, but as long as you know where your error log files are for your dev server it offers a quick and concise way to see what is going wrong that will also serve you in an eventual production environment.
As far as handling empty form fields you can take a multichannel approach here, HTML5 forms let you specify a field as required and block execution for invalid forms. Javascript validation is another option on the client side. It is always good to validate and sanitize your data on the server side as well though, and for this php has a few useful tools (filter_var, filter_input) to help with this task, additionally all of the request/server superglobals are iterable so rather than set up a conditional chain you can loop them and avoid repetitive code.
PHP
<?php
$newRecord = false;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
try {
list($errors, $inputs) = cleanInputs($_POST);
if (!$errors['valid']) {
throw new Exception(json_encode($errors));
}
// using instantiation in the same file for the example.
$mysqli = new mysqli('host', 'user', 'password', 'schema');
if (!$mysqli) {
throw new Exception("({$mysqli->connect_errno}) {$mysqli->connect_error}");
}
// why is your form asking for Gender and URL if you aren't using them?
$insertQuery = "INSERT INTO subscriptions (Name, Email, Comment, Subscription) VALUES (?, ?, ?, ?)";
$stmt = $mysqli->prepare($insertQuery);
if (!$stmt) {
throw new Exception("({$mysqli->errno}) {$mysqli->error}");
}
$stmt->bind_param('ssss', $inputs['Name'], $inputs['Email'], $inputs['Comment'], $inputs['Subscription']);
$stmt->execute();
$newRecord = ($stmt->affected_rows > 0) ? 'Record added to database' : 'Record failed to insert to database';
} catch (Exception $e) {
// Here is where you would set your error variables for the html form.
error_log($e);
}
}
function cleanInputs($inputs)
{
$keys = ['Name', 'Email', 'Website', 'Comment', 'Subscription',];
$clean = [];
$errors = ['valid' => true];
foreach ($keys as $key) {
if (empty($inputs[$key])) {
$errors[$key] = "{$key} is required";
$errors['valid'] = false;
continue;
}
if (in_array($key, ['Name', 'Comment', 'Subscription', 'Gender'])) {
$clean[$key] = trim(filter_var($inputs[$key], FILTER_SANITIZE_STRING));
continue;
} else if ($key === 'Email') {
$filter = filter_var($inputs[$key], FILTER_VALIDATE_EMAIL);
if (!$filter) {
$errors[$key] = 'Invalid email format';
$errors['valid'] = false;
continue;
}
$clean[$key] = trim($filter);
} else if ($key === 'Website') {
$filter = filter_var($inputs[$key], FILTER_VALIDATE_URL);
if (!$filter) {
$errors[$key] = 'Invalid URL Format';
$errors['valid'] = false;
continue;
}
$clean[$key] = trim($filter);
}
}
return [$errors, $clean];
}
?>
Edit
Expanding to help answer below question.
The cleanInputs() method will return both clean keys and any errors, so from there in your catch you would need to fill those error variables in. I would probably suggest setting default input values at the top of the file before processing and then resetting them in the error handler if they need to exist.
<?php
$newRecord = false;
$name = '';
$email = '';
$website = '';
$comment = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// ... back to original example
then update your HTML with some error handler conditionals, use alternative syntax (personal opinion here, looks cleaner to me if you have to put logic into your templating)
<label for="Name">Name: </label>
<input type="text" name="Name" value="<?= $name ?>">
<?php if (isset($nameErr) && $nameErr !== false) : ?>
<span class="error">* <?= $nameErr ?></span>
<?php endif; ?>
<br><br>
and update your catch statement
} catch (Exception $e) {
if (!$errors['valid']) {
// repeat for errors.
$nameErr = (isset($errors['Name'])) ? $errors['Name'] : false;
if (!$nameErr) {
$name .= $inputs['Name'];
}
}
error_log($e);
}

How to return any kind of data from PHP Script Page to HTML Page without using JQuery or AJAX?

I am currently trying to make a HTML form page [main.html], which will take following input :
Name, Email, and Contact Number
when the data is submitted, it will go to PHP script [validate.php] where it will be validated. like whether the name contains any invalid character set or number etc.
if the validation fails, it should return error msg e.g "Data Validation Fails".
and if the validation is successful, PHP page should return the data to main.html where the received data needs to be displayed and user is asked to confirm it again.
Once the data is confirmed by the User, it will be send data to another PHP Script file [store.php] for storing in a text file [e.g. UserDb.txt].
I am very much new to PHP and HTML with no knowledge of JQuery. I can somehow prepare main.html and store.php but heavily confused for validate.php page.
Please tell me how can i send back the data from PHP page [validate.php] to HTML page [main.html] to ask for confimation ??
Please do not suggest solutions involving JQuery and AJAX.
There are lot of webpages for that which I can find on Internet, but i could not find any solution particularly for this case. I Hope it is possible to send data back to HTML Page from PHP Script.
Form action tag is there for that action. Lets see on an example. here we have our form main_form.php;
<form action="validation.php" method="post">
<h2>Form</h2>
<span class="error">* required field.</span>
Name:
<input name="name" type="text" value="">
<span class="error">* <?php echo $nameError;?></span>
E-mail:
<input name="email" type="text" value="">
<span class="error">* <?php echo $emailError;?></span>
Gender:
<input name="gender" type="radio" value="female">Female
<input name="gender" type="radio" value="male">Male
<span class="error">*<?php echo $genderError;?></span>
Website:
<input name="website" type="text" value="">
<span class="error"><?php echo $websiteError;?></span>
Comment:
<textarea cols="40" name="comment" rows="5">
</textarea>
<input name="submit" type="submit" value="Submit">
</form>
Now lets see how we validate on validation.php;
<?php
// Initialize variables to null.
$nameError ="";
$emailError ="";
$genderError ="";
$websiteError ="";
// 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["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check address syntax is valid or not(this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i",$website)) {
$websiteError = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
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;
}
//php code ends here
?>
If there is an error this script will return error to the our main_form.php.For errors use css to show them in red like below error.css;
.error{
color:red
}
TL;DR: Set form action to validation.php. Keep it simple.
To start and set a session variabl :
session_start(); //at top of page
$_SESSION['name_of_field'] = $_POST['name_of_field']; //do checks on the post data!
To use a session varible :
session_start(); //at top of page
$my_new_value = $_SESSION['name_of_field'];
you will get data in varible.
Or you can send data via URL
Write this in php
header('Location: http://yoursite.com/page2.php?name='.$name.'&email='.$email);
and get
$name = $_GET['name'];
$email = $_GET['email'];
You may also try
Rename your main.html to main.php then include validate.php above your form tag to display errors above form. Thus, your form action would be self or blank
<?php include "validate.php"; ?>
<form action ="" method ="post"... >
But if there are no errors, then from validate.php you can redirect to the index.php for user confirmation using
header('Location: index.php?name='.$name);
The value of name can be accessed using $_GET['name'];

php validation on submit when jump from one page to another

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 :)

PHP script not validating input

Why is this script not validating e-mail address, name and phone number? It is sending the e-mail, but not notifying me of the intentional errors in the input fields. (This script is called from html form tag).
<?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
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["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["phone"])) {
$phone = "";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number is valid (this regular expression also allows dashes in the phone number)
if (!preg_match("/^[0-9+'('+')'+ '-' ]*$/",$phone)) {
$phoneErr = "Invalid Phone Number";
}
}
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
mail( "omitted#omitted.com", "Contact Us Inquiry",
$message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}
?>
updated 6/23/15 almost midnight EDT
Form now validates input, but I want it prettier.
Posting contents of HTML form tag and script tag to show you that I want the email, name and phone number errors to appear to the right of the input boxes for those fields and if there are errors, I want to stay on the Contact_Us page. How do I do that? (Also posting working php script below the HTML form contents.)
In Head tag:
<style>
.error {color: #00a261;}
</style>
In Body tag:
<p><span class="error">* required field. </span></p>
<form method="post" name="contact_us_form" action="contact_us_e_mail.php">
<div align="center">
Email: <input name="email" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php
echo $emailErr; ?>
</span><br /><br />
Name: <input name="name" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php echo $nameErr; ?>
</span><br /><br />
Phone: <input name="phone" type="text" border-style="solid" border-width="1px" style="border-color:#00a261" value=""/><span class="error"> *
<?php echo $phoneErr; ?>
</span><br /><br />
Message:<br />
<textarea name="message" border-style: solid style="border-color:#00a261" rows="15" cols="80">
</textarea>
<br />
<input type="submit" value="Submit"/>
</form>
Revised php script (called contact_us_e_mail.php):
<?php
// define variables and set to empty values
$emailErr = $nameErr = $phoneErr = "";
$email = $name = $phone = $message = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
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. Please use browser's back button and correct.";
}
}
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 in Name. Please use browser's back button and correct.";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if phone number is valid (this regular expression also allows dashes in the phone number)
if (!preg_match("/^[0-9+'('+')'+'-']*$/",$phone)) {
$phoneErr = "Invalid Phone Number. Please use browser's back button and correct.";
}
}
$email = $_REQUEST['email'] ;
$name = $_REQUEST['name'] ;
$phone = $_REQUEST['phone'] ;
$message = $_REQUEST['message'] ;
if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
mail( "omitted#omitted.com", "Contact Us Inquiry",
$message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}else{
echo $emailErr, "<br />";
echo $nameErr, "<br />";
echo $phoneErr, "<br />";
//$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
//header( "Location: http://omitted.com/Contact_Us.html" );
}
}
?>
Well you are setting the variables $nameErr, $phoneErr, $emailErr but you are never testing them.
You should wrap your mail statement in an if like this:
if($nameErr == '' && $phoneErr == '' && $emailErr == ''){
mail( "omitted#omitted.com", "Contact Us Inquiry", $message, "From: $email" );
header( "Location: http://omitted.com/ThankYou.html" );
}else{
$errorList = $nameErr . ' ' . $phoneErr . ' ' . $emailErr;
header( "Location: http://omitted.com/errors.php?errorList=" . $errorList );
}
Here's one approach to cracking that particular nut. The key is to check for the existance of the form's vars at the beginning of the script, before deciding what to present to the user. Yet another alternative would be to submit the form using the FormData object and AJAX. You could return a JSON object and then with JS on the client-side, decide whether to hide/show error messages and to re-direct to another page upon success, if desired.
The way that the die functions is one of the important keys to such an approach. As mentioned in the comments, it stops any further processing of the file - whether it be simply emitting html or if it be evaluating php code.
If the 'validation' (that I dont perform) fails, you'll get an asterisk next to the fields with problems. It will also throw the acceptable fields back into their inputs in the form, avoiding the need to type all of the info again for the sake of an error in just one of the inputs.
Just throw it onto a server and have a play. I'm a bit in two minds about such an approach. On one hand, it ties everything all together in a single location. On the other hand, you can end up with 4 languages in a single file (php,html,css,js) and something that can fairly quickly become a little er, unpleasant to maintain.
test.php
<?php
/*
sample that contains a form that will sumbit to itself
*/
// nothing entered in the POST array - this means the page has been loaded as a result of a request originating
// somewhere _other_ than the form in this page.
// we'll need to display the page ready for a 'first-visit'
if (count($_POST) == 0)
{
//echo ('$_POST array is empty!<br>');
$username = $email = $message = '';
}
// no validation here, I'm assuming all are okay. You need to validate for yourself in this block of code.
// you'll notice that submitting an empty form gives us 3 vars in the POST array, all of which are empty strings
else
{
$username = $email = $message = '';
if (isset($_POST['username']) == true)
$username = $_POST['username'];
if (isset($_POST['email']) == true)
$email = $_POST['email'];
if (isset($_POST['message']) == true)
$message = $_POST['message'];
// use this block or the 7 lines above - they have the same effect.
/*
$username = isset($_POST['username']) == true ? $_POST['username'] : "";
$email = isset($_POST['email']) == true ? $_POST['email'] : "";
$message = isset($_POST['message']) == true ? $_POST['message'] : "";
*/
if ( strlen($username) == 0)
$usernameNotPresent = true;
if ( strlen($email) == 0)
$emailNotPresent = true;
if ( strlen($message) == 0)
$messageNotPresent = true;
if (( isset($usernameNotPresent)==false) && (isset($emailNotPresent)==false) && (isset($messageNotPresent) == false))
{
doSendMail();
// execution/parsing of the file will stop here. This has 2 effects.
// 1. Any further php code wont be interpreted and then run
// 2. Any html that follows a call to die wont be shown.
// Therefore, if we get here that means we've sent the email and there's no use in showing the
// email form.
// provided nothing has been output yet, you could also re-direct to another page with a call
// to the function header
die;
}
}
function doSendMail()
{
// ToDo:
// send the email here
// print a message telling the user of the outcome of trying to send the email.
echo "<p>Email successfully sent, please check your inbox</p>";
}
?>
<!doctype html>
<html>
<head>
<script>
</script>
<style>
.wrapper
{
display: inline-block;
}
#myForm
{
text-align: center;
}
#myForm > input, #myForm > textarea
{
/* display: block; */
margin-bottom: 16px;
width: 170px;
text-align: left;
}
#myForm > input[type='submit']
{
width: 50%;
text-align: center;
}
</style>
</head>
<body>
<div class='wrapper'>
<form id='myForm' method='post' action='' > <!-- an empty action attribute submits the form back to itself -->
<?php
if (isset($usernameNotPresent))
echo "<input type='text' name='username' placeholder='enter username'><span class='error'>*</span></br>";
else
echo "<input type='text' name='username' placeholder='enter username' value='$username'></br>";
?>
<?php
if (isset($emailNotPresent))
echo "<input type='text' name='email' placeholder='enter email address'><span class='error'>*</span></br>";
else
echo "<input type='text' name='email' placeholder='enter email address' value='$email'></br>";
?>
<?php
if (isset($messageNotPresent))
echo "<textarea name='message' placeholder='enter your message'></textarea><span class='error'>*</span></br>";
else
echo "<textarea name='message' placeholder='enter your message'>$message</textarea></br>";
?>
<div><input type='submit' value='GO'/></div>
</form>
</div>
</body>
</html>

Categories