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 :)
Related
I am learning PHP through w3schools. I am little bit confused of the execution flow of the page. I will attach a code example from w3schools.
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}
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"]);
}
}
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 htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website: <input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="other">Other
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</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;
?>
</body>
</html>
Can anyone explain how the execution flow goes on this form handling. Browser can't run the php script. In this example superglobal $_SERVER["PHP_SELF"] used to refer the same html page. when we try to submit the page with empty field it shows the error message in screen. This is happening due to the fact php variable got its error value after submission. I think that after triggering the submit button. This page makes a request to the same page in the server using POST method and in the server we access the same form value using superglobal $_POST["name"],["email"] etc.. and finally the server throws the new html page. Am i right? or this validation is happening entirely in the frontend.
In php the validation is happening entirely in the server ..
The frontend only validate things when JavaScript involved or you add field attributes like required , min , max.
I think w3 is good source to check small code snippets. but it's not good source to learn
When the user visits the Visitor Log page, they should be able to see a prompt asking them to enter their name. Upon submitting the form, the same page should display a completely different message welcoming the user to the web page. When the user refreshes the page, the process starts over.
This is what I have tried so far, it works, but I still don't understand how I would display a whole new message after the input.
Here is the code I have I need help with only using PHP to have the correct desired result
Attempt
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
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";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p2 id="example-id-name" class="centered-text "></p>
<p><span class="error"></span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" value="<?php echo $name;?>">
<span class="error"> <?php echo $nameErr;?></span>
<br> <br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "$name";
echo "<br>";
?>
Where you're echoing name, you can check whether you have it or not and choose the message to display
<?php
if($name) {
echo "Hi $name!\n Welcome to our store!"
}
else {
echo "Please enter your name"
}
echo "<br>";
?>
You can write inline php and functions.
Code:
<?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');
$err = "";
# If client post a name, then validate the name
if ($method === "POST"){
$name = $_POST["name"] ?? "";
validate_name($name, $err);
}
?>
<!-- The form -->
<form method="post">
<label>
<input type="text" name="name" value="<?=$name ?? ""; ?>">
</label>
<!-- Show if error -->
<?php if (!empty($err)) { ?>
<span class="error">
<?=$err ?>
</span>
<?php } ?>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<?php if (isset($name) && empty($err)) { ?>
<p>Hi <?=$name ?>!</p>
<p>Welcome to our store!</p>
<?php } ?>
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
I made a website using css, html, javascript and a little php. I have it hosted on a hosting site with a domain name, but I'm having issue with the server side validation for the form.
It's just a simple contact form:
First Name
Last Name
Email
Message (textarea)
Submit button
I have javascript validation and it works fine. The form won't submit at all unless the correct amount of characters are input, but obviously that's useless if the user has js disabled. I've also finally gotten the form to email to my personal email using php... But obviously I need server side validation as well.
Today was my first day really getting into php and I was hoping to have the php validation done by today, but of all the videos I watched, I just came away more confused. All I want to do is just make it so that if the user has javascript disabled for whatever reason, or if he leaves the fields blank, the form won't submit...
Anyeay, I was working on this all day today with the intention of getting the form to send to my email, I finally accomplished that. Then realized I had no server side validation. I spent a few hours researching it and attempting it to no avail. Can anyone here just give me the php validation code for the kind of form I described above? It's for my business website so the sooner I can have a working contact form on it, the better...
Here is the html contact form I made.
<form action="message_sent.php" method="POST" onSubmit="return validateTextbox();">
<p class="message">
<div class="row">
<label for="firstname"><!--First Name (Required):--> </label>
<input type="text" id="firstname" name="first_name" size="40" placeholder="First Name (Required)"></br> </br> </div>
<div class="row">
<label for="lastname"><!--Last Name (Required):--> </label>
<input type="text" id="lastname" name="last_name" size="40" placeholder="Last Name (Required)"/> </br> </br></div>
<div class="row">
<label for="email"><!--Your Email (Required):--></label>
<input type="email" id="email" name="email" size="40" placeholder="Email (Required)"/> </br> </br></div>
<!--<p class="yourMessage">Your Message (10 Character Minimum):</p>-->
<textarea id="theform" rows="30" cols="80" name="message" placeholder="Your Message (10 Character Minimum):"></textarea></br>
</p>
<input type="submit" name="submit" onclick="return val();" value="SUBMIT">
</form>
</body>
</html>
Here is the javascript validation:
/*============================ CONTACT US PAGE ==========================*/
function validateTextbox() {
var box = document.getElementById("firstname");
var box2 = document.getElementById("lastname");
var box3 = document.getElementById("email");
var box4 = document.getElementById("theForm");
if (box.value.length < 1 || box2.value.length < 1 || box3.value.length < 5){
alert("You must enter a value");
box.focus();
box.style.border = "solid 3px red";
box2.focus();
box2.style.border = "solid 3px red";
box3.focus();
box3.style.border = "solid 3px red";
return false;
}
}
function val(){
if(document.getElementById("theform").value.length < 10
&& document.getElementById("theform").value.length > 0){
alert("You must enter at least 50 characters. Tell us what you need so we can better assist you.");
return false;
}
else if(document.getElementById("theform").value.length === 0){
alert("You cannot submit an empty form.");
theform.focus();
theform.style.border = "solid 3px red";
return false;
}
}
/*function val(){
if(document.getElementById("theform").value==null || document.getElementById("theform").value==""){
alert("The Message field cannot be blank.");
return false;
}
*/
/*
*/
/*=======================|| box4.value.length < 70) ================================================ */
/*========= CONTACT PAGE========================================*/
/*
function contactPage(){
alert("This Contact Form is NOT OPERATIONAL.");
Here is the php submission success page... the code I used to have the form send to my email:
<?php
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$email=$_POST['email'];
$message=$_POST['message'];
$to="default#email.com";
$subject="A visitor has sent you a new message";
$body="You have received a message from: \n\n
First Name: $first_name\n
Last Name: $last_name\n
Email: $email\n\n
MESSAGE: $message";
mail($to, $subject, $body);
print "<p>Message Sent! <a href='index.html'>Click. here</a> to return to the homepage</p>"
?>
Simple and complete example:
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
//Define variable as empty to avoid "undefined variable error".
$FnameErr = $LnameErr = $emailErr = ""; //Each variable contain error string of specific field.
$fname = $lname = $email = $message = ""; //Main inputed data of specific field
if ($_SERVER["REQUEST_METHOD"] == "POST") { //check if request is posted.
//First name check
if (empty($_POST["fname"])) { // check if empty then assign a error string in spacific variable
$FnameErr = "First Name is required";
}else{ // if not empty then store as right data
$fname = filter_data($_POST["fname"]); //filter with unexpected special char and trim.
}
//Last name
if (empty($_POST["lname"])) { // check if empty then assign a error string in spacific variable
$LnameErr = "Last Name is required";
}else{ // if not empty then store as right data
$lname = filter_data($_POST["lname"]); //filter with unexpected special char and trim.
}
//email
if (empty($_POST["email"])) { // check if empty then assign a error string in spacific variable
$emailErr = "Email is required";
} else {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { // validate email with php build-in fucntion.
$emailErr = "Invalid email format";
}else{ // if not empty and valide email then store as right data
$email = filter_data($_POST["email"]); //filter with unexpected special char and trim.
}
}
//message with no validation
if (empty($_POST["message"])) {
$message = "";
} else {
$message = filter_data($_POST["message"]);
}
//Database query
if($FnameErr =="" && $LnameErr =="" && $emailErr==""){
//MYSQL insert statement that you know
// $sql = "INSERT INTO tablename .................."; values = $fname; $lname; $email; $message;
}
}
// A function to trim data and remove special charecter
function filter_data($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
First Name: <input type="text" name="fname" value="">
<span class="error">* <?php echo $FnameErr;?></span><br><br>
Last Name: <input type="text" name="lname" value="">
<span class="error">* <?php echo $LnameErr;?></span><br><br>
E-mail: <input type="text" name="email" value="">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Message: <textarea name="message" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $fname;
echo "<br>";
echo $lname;
echo "<br>";
echo $email;
echo "<br>";
echo $message;
?>
</body>
</html>
This is just a basic empty check validation.
Validations in PHP are not very difficult.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(trim($_POST['firstname']) === ''){
echo 'Please enter firstname';
}
}
You can also learn some validations here
http://www.w3schools.com/php/php_form_validation.asp
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'];