Submit functionality using php to prevent submission upon invalid inputs - php

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!

Related

Producing error messages in php validation

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';
}

Submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX

I want to create a submit form (contact form) that links with my SQL database and replaces the submission form with a message on the same page via AJAX. I've tried W3C schools and a couple of step by step guides but still struggling. So far, I've written the HTML for and Validation and connected to my SQL database. However, I'm not sure what steps to take next. I'm new to coding and not sure what to do next...
<?php
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = "";
$name = $email = $phone = $comment = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Telephone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="form">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["register.php"])?>">
<fieldset>
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>
Phone: <input type="tel" name="phone" value="<?php echo $phone;?>">
<span class="error">* <?php echo $phoneErr;?></span>
<br><br>
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
<br><br>
<button type="submit"> Submit</button>
</fieldset>
</form>
</div>
I will do it simply like this:
Create an empty div before Form's fieldset:
<div class="col-xs-12 col-sm-9 col-md-8 col-lg-8 conForm">
<h4>Shoot a message!</h4>
**<div id="message"></div>**
<form method="post" action="php/contact.php" name="cform" id="cform">
<input name="name" id="name" type="text" class="col-xs-12 col-sm-6 col-md-6 col-lg-6" placeholder="Your name..." >
<input name="email" id="email" type="email" class=" col-xs-12 col-sm-6 col-md-6 col-lg-6 noMarr" placeholder="Your email..." >
<textarea name="comments" id="comments" cols="" rows="" class="col-xs-12 col-sm-12 col-md-12 col-lg-12" placeholder="Your message..."></textarea>
<input type="submit" id="submit" name="submit" class="submitBnt" value="Send message">
<div id="simple-msg"></div>
</form>
</div>
in PHP print message like this after email sent:
if(mail($address, $e_subject, $msg, $headers)) {
// Email has sent successfully, echo a success page.
echo "<fieldset>";
echo "<div id='success_page'>";
echo "<h3>Email Sent Successfully.</h3>";
echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>";
echo "</div>";
echo "</fieldset>";
} else {
echo 'ERROR!';
}
As you asked, i think you are totally new in coding world.so that's why i write full code in one page. create a .php file and paste this code
<html>
<head>
<script type="text/javascript">
function validateName() {
var name = document.getElementById('contact-name').value;
if(name.length == 0) {
producePrompt('Name is required', 'name-error' , 'red')
return false; }
if (!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/)) {
producePrompt('First and last name, please.','name-error', 'red');
return false; }
producePrompt('Valid', 'name-error', 'green');
return true;}
function validatePhone() {
var phone = document.getElementById('contact-phone').value;
if(phone.length == 0) {
producePrompt('Phone number is required.', 'phone-error', 'red');
return false; }
if(phone.length != 10) {
producePrompt('Include area code.', 'phone-error', 'red');
return false; }
if(!phone.match(/^[0-9]{10}$/)) {
producePrompt('Only digits, please.' ,'phone-error', 'red');
return false; }
producePrompt('Valid', 'phone-error', 'green');
return true;}
function validateEmail () {
var email = document.getElementById('contact-email').value;
if(email.length == 0) {
producePrompt('Email Invalid','email-error', 'red');
return false; }
if(!email.match(/^[A-Za-z\._\-[0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/)) {
producePrompt('Email Invalid', 'email-error', 'red');
return false; }
producePrompt('Valid', 'email-error', 'green');
return true;}
function validateMessage() {
var message = document.getElementById('contact-message').value;
var required = 10;
var left = required - message.length;
if (left > 0) {
producePrompt(left + ' more characters required','message-error','red');
return false; }
producePrompt('Valid', 'message-error', 'green');
return true;}
function validateForm() {
if (!validateName() || !validatePhone() || !validateEmail() || !validateMessage()) {
jsShow('submit-error');
producePrompt('Please fix errors to submit.', 'submit-error', 'red');
setTimeout(function(){jsHide('submit-error');}, 2000);
return false; } else { }
}
function jsShow(id) {
document.getElementById(id).style.display = 'block'; }
function jsHide(id) {
document.getElementById(id).style.display = 'none';}
function producePrompt(message, promptLocation, color) {
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;}
</script>
</head>
<form action="" method="POST">
<div class="form-group">
<label for="contact-name">Name</label>
<input type="text" class="form-control" id="contact-name" name="name" placeholder="Enter your name.." onkeyup='validateName()'>
<span class='error-message' id='name-error'></span>
</div>
<div class="form-group">
<label for="contact-phone">Phone Number</label>
<input type="tel" class="form-control" id="contact-phone" name="phone" placeholder="Ex: 1231231234" onkeyup='validatePhone()'>
<span class='error-message' id='phone-error'></span>
</div>
<div class="form-group">
<label for="contact-email">Email address</label>
<input type="email" class="form-control" id="contact-email" name="email" placeholder="Enter Email" onkeyup='validateEmail()'>
<span class='error-message' id='email-error'></span>
</div>
<div class="form-group">
<label for='contactMessage'>Your Message</label>
<textarea class="form-control" rows="5" id='contact-message' name='message' placeholder="Enter a brief message" onkeyup='validateMessage()'></textarea>
<span class='error-message' id='message-error'></span>
</div>
<button onclick='return validateForm()' name="submit" value="submit" class="btn btn-default">Submit</button>
<span class='error-message' id='submit-error'></span>
<span class='success-message' id='submit-success'></span>
<?php
if (isset($_POST['submit']) && (!empty($_POST['submit']))) {
$servername = "localhost";
$username = "root"; //change this to your username
$password = ""; //change this to your database password
$dbname = "db"; //change this to your database name
$name = "$_POST[name]";
$phone = "$_POST[phone]";
$email = "$_POST[email]";
$message = "$_POST[message]";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);}
//insert data into table named guestbook
$sql = "INSERT INTO guestbook (name, email, phone, message) VALUES ('$name', '$email', '$phone', '$message')";
if ($conn->query($sql) === TRUE) {
echo "<br/><font color=green>Your Comment Successfully Sent</font>";
} else {
echo "Error updating record: " . $conn->error; }
$conn->close();}
?>
</form>
</body>
</html>
In your DATABASE, create a database whatever you named but dont forget to change in php file $dbname = ""; and create table with these code:
CREATE TABLE guestbook
(
id int NOT NULL AUTO_INCREMENT,
name varchar(255),
email varchar(255),
phone varchar(255),
message varchar(255),
PRIMARY KEY (id)
);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error){
die("Connection failed:".$conn->connect_error);
}
$sql = "INSERT INTO MyGuests (name, email, phonenumber,comment)
VALUES ($name , $email ,$phone,$comment)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: ".$sql."<br>".$conn->error;
}
$conn->close();
Where put you $comment , $name and others and also configure you database name, password and database table.

How do I add PHP validation to my contact for

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

how to get data after self validation in php

how to pass the collected input to another page after self validate in php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body>
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
if($_SERVER["REQUEST_METHOD"] =="POST"){
$valid = true;
if(empty($_POST["forename"])){
$forenameErr = "Forename is required";
$valid = false; //false
} else {
$forename = test_input($_POST["forename"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["surname"])){
$surnameErr = "Surname is required";
$valid = false; //false
} else {
$surname = test_input($_POST["surname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "Only letters and white space allowed";
}
}
if(empty($_POST["postalAddress"])){
$postalAddressErr =" Please enter postal address";
$valid = false; //false
} else {
$postalAddress = test_input($_POST["postalAddress"]);
}
if(empty($_POST["landLineTelNo"])){
$landLineTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$landLineTelNo = test_input($_POST["landLineTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$landLineTelNo)) {
$landLineTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["mobileTelNo"])){
$mobileTelNoErr = "Please enter a telephone number";
$valid = false; //false
} else {
$mobileTelNo = test_input($_POST["mobileTelNo"]);
// check if invalid telephone number added
if (!preg_match("/^[0-9 ]{7,}$/",$mobileTelNo)) {
$mobileTelNoErr = "Invalid telephone number entered";
}
}
if(empty($_POST["email"])){
$emailErr = "Email is required";
$valid = false; //false
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if(empty($_POST["sendMethod"])){
$sendMethodErr = "Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//if valid then redirect
if($valid){
header('Location: userdetail.php');
exit();
}
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error">* <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error">* <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> </span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> * <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" placeholder="example:012-3456789" value="<?php echo $mobileTelNo;?>" />
<span class="error"><?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>" placeholder="example:123#hotmail.com"/>
<span class="error"> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error">* <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="checkbox" value="check" id="agree" />
I have read and agree to the Terms and Conditions and Privacy Policy
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</fieldset>
</form>
</div>
</body>
</html>
here is my php form...
it can validate itself in the same page but couldn't pass the data to another php page....
here is my another php code...
<?php
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr =$mobileTelNoErr = $sendMethodErr = "";
$forename = $surname = $email = $postalAddress = $landLineTelNo = $mobileTelNo = $sendMethod = "";
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
echo "<p>Email: $email</p>";
echo "<p>Post Address: $postalAddress</p>";
echo "<p>Landline: $landLineTelNo</p>";
echo "<p>Mobile : $mobileTelNo</p>";
echo "<p>Contact method: $sendMethod";
?>
You can use $_SESSION variables.
PHP $_SESSIONS
PHP Sessions and Cookies
So after the users has been validated set $_SESSION['surname'] = $surname;
Then on the top of each page add session_start(); to the top.
Then Under that add
if (isset($_SESSION['surname'])) {
$surname = $_SESSION['surname'];
} else {
die();
}
View the PHP docs for a more thorough understanding.
You may also want to look into setting up a MYSQL database if you want users to be able to create accounts.
Edit: form page
if($valid){
$_SESSION['surname'] = $surname;
$_SESSION['postalAddress'] = $postalAddress;
header('Location: userdetail.php');
exit();
}

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

Categories