I wanted to create a registration validation system (to make sure that the user registered has valid info) with PHP and Javascript Alert Boxes. Each time a user does not do a field correctly, I want him to get an alert box saying that it is incorrect. So here it is:
Code #1 - For generating alerts in PHP (This is for the event in the button).
function alert($string)
{
echo "javascript:alert('$string');";
}
Code #2 - PHP placed inside the onclick="" attribute for the submit button.
if (!isset($fname) || empty($fname))
{
alert('Please enter your first name!');
}
elseif (!isset($lname) || empty($lname))
{
alert('Please enter your last name!');
}
elseif (!isset($gender) || empty($gender))
{
alert('Please specify your gender!');
}
elseif (!isset($phone) || empty($phone) || strlen($phone) != 10)
{
alert('Please enter your correct Phone Number!');
}
elseif (!isset($user) || empty($user) || strlen($user) > 10 || strlen($user) < 5)
{
alert('Please enter a Username that is 5-10 characters long!');
}
elseif (!isset($pass) || empty($pass) || strlen($pass) > 10 || strlen($pass) < 5)
{
alert('Please enter a Password that is 5-10 characters long!');
}
elseif (!isset($repass) || empty($repass) || $pass != $repass)
{
alert('Please repeat your Password');
}
else
{
$query = mysql_query($query_send_form);
query_error($query);
}
As you have probably realised, the variables are actually equal to the $_POST values of the field in the form.
So the problem is that the onclick of the button is ALWAYS equal to onclick="
javascript:alert('Please enter your first name!');" It wouldn't change.
Please don't give me a complete javascript alternative to the system, I want to learn PHP for now.
Thanks for your help in advance.
EDIT #1
An important thing I forgot to mention was that the form target is just an iframe on the same page, so that the content the user has entered stays while he is being shown the error.
<form method="post" target="frame" action="register.php">
register.php is the same page where the form HTML and the validation PHP is.
EDIT #2
The data is being posted. Here are the declared varibles:
#$fname = $_POST['fname'];
#$lname = $_POST['lname'];
#$gender = $_POST['gender'];
#$phone = $_POST['phone'];
#$user = $_POST['user'];
#$pass = $_POST['pass'];
#$repass = $_POST['repass'];
You really shouldn't do that kind of validation like that...
Anytime you want to tell the user something is invalid because of logic rules, it is done with javascript on the front side. There are some good plugins out there written in either jquery or javascript out here. You can also make something simple on your own. This helps the user because then they don't have to submit the page to find out that their password isn't long enough.
You still need to do validation after POST and before putting things in the database because of sql injection. That kind of validation is a little different because you're just looking for things that are harmful.
This example is self-contained. The messages go to a div instead of alerts.
<?php
$message = "";
$submit = (isset($_POST['submit'])) ? $_POST['submit'] : '';
if (!empty($submit)) {
$message = "thanks for submitting the form!";
}
?><div id="errors"><?php echo $message ?></div>
<form id="my_form" name="my_form" action="" method="post">
<div style="display:inline-block;">Name<br/>
<input name="first_name" type="text" size=8 class="required"/>
<input name="last_name" type="text" size=16 class="required"/>
</div>
<div style="display:inline-block;">Gender<br/>
<select name="gender" class="required">
<option value=''></option>
<option value='M'>M</option>
<option value='F'>F</option>
</select>
</div>
<div style="display:inline-block;">Phone Number<br/><input name="phone" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Username<br/><input name="username" type="text" class="required"/></div><br/>
<div style="display:inline-block;">Password<br/><input name="password" type="password" class="required"/></div>
<div style="display:inline-block;">Repeat Password<br/><input name="repeat_password" type="password" class="required"/></div><br/>
<div style="display:inline-block;">Description<br/><textarea name="description"></textarea></div><br/>
<button type="submit">Submit</button>
<input type="hidden" name="submit" value="submit"/>
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style> .invalid {border-color:red}</style>
<script>
$(document).ready(function(){
$("#my_form").submit(function(e){
var messages = perform_validation();
if (messages.length!==0) {
$("#errors").empty();
$.each(messages,function(i,msg){
$("#errors").append(msg+"<br/>");
});
e.preventDefault();
return false;
}
// else continue to submit form normally
});
function perform_validation()
{
var messages = [];
$("#my_form :input.required").removeClass("invalid");
$("#my_form :input.required").each(function(){
if ($(this).val().length===0) {
$(this).addClass("invalid");
var name = $(this).attr('name').replace('_',' ');
messages.push("Please provide a "+name+".");
}
});
var password = $("input[name='password']").val();
if (!(password.length>=5 && password.length<=10)) {
messages.push("Password length must be between 5 and 10 characters.");
}
else {
if (password!=$("input[name='repeat_password']").val()) {
messages.push("Repeat password doesn't match first password.");
}
}
return messages;
}
});
</script>
Unless you have magic quotes turned on (and I hope you don't), your values such as $fname will always be undefined. You probably want to replace those with $_POST['fname'].
On a side note, you can use just empty() without !isset() since empty() will return FALSE if the value is not set.
Related
If for example a username isn't filled in the user is given an error stating so, but after pressing submit they're thrown to another page with the error.
How would I go around keeping the error on the same page as the registration form and keeping all the text entered by the user after submit?
Registration PHP:
<?php
require 'db_connect.php';
$count = 0;
if (isset($_POST['username']))
{
$username = $_POST['username'];
if (!empty($username))
{
$count++;
}
else
{
echo 'Please enter a username';
echo "<br>";
}
}
if (isset($_POST['email']))
{
$email = $_POST['email'];
if (!empty($email))
{
$count++;
}
else
{
echo 'Please enter an email';
echo "<br>";
}
}
if (isset($_POST['password']))
{
$password = $_POST['password'];
if (!empty($password))
{
$count++;
}
else
{
echo 'Please enter a password';
echo "<br>";
}
}
if(strlen($username) > 25)
header('Location: registration.php');
$hashword = password_hash($password,PASSWORD_DEFAULT);
if($count == 3 )
{
$query = "INSERT INTO member ( username, password, email)
VALUES ( '$username', '$hashword', '$email');";
header('Location: login.html');
}
else {
echo '<b>You will be redirected shortly</b>';
echo "<br>";
echo '<b>Please enter ALL details correctly</b>';
header( "refresh:5;url=registration.php" );
}
$result = mysqli_query($connection, $query) or die(mysqli_error($connection));
?>
Registration Form:
<!doctype html>
<html lang="en">
<head>
<title>Gumby template file</title>
<meta charset="utf-8" />
<script data-touch="gumby/js/libs" src="gumby/js/libs/gumby.min.js"></script>
<script src="gumby/js/libs/jquery-2.0.2.min.js"></script>
<link rel="stylesheet" href="gumby/css/gumby.css">
<script src="gumby/js/libs/modernizr-2.6.2.min.js"></script>
<link rel="stylesheet" href="forumhomepage_style.css">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<form name="register" action="register.php" method="post">
<tr>
<td>Username: </td>
<td><input type="text" name="username" maxlength="25" /></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Password: </td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>
It depends on at what level do you want to do this.
Validating that the different data is not empty and has information that makes sense (like the password is at least 7 chars long) can be done via javascript before sending the form data, this way you can stop the form to be sent. You can use jQuery Plugin Validator to help you do this.
But other validations like the insert has failed only can be done at server side, if you need also not to redirect in this case then you have to use ajax to load the data and then refresh the website info without reloading it.
I prefer to only do an initial check with javascript and send the user to the results page. But I also keep the validations as this one of the password length in the php because, even though now a days it's really strange, a user can disable javascript and I don't wana have surprises when checking the database values. But, another example, if you have lots of users you could check that the user does not exist to warn the user at the very first moment before the form is sent and this can only be done performing an ajax call.
You should know how to do both things and decide depending on what you want to do on your projects.
In your case, I would leave the php validations as they are now and check the same (non empty values) in javascript on the form submit event calling event.preventDefault() if an error has been detected.
$('form[name="register"]').submit(function( event ) {
if ($('input[name="username"]').is(":empty")) {
// append a "Username can not be empty message somewhere on your page
event.preventDefault();
}
// I let you finish the jquery code...
});
This example uses jQuery lib. but you can do it without it with just javascript if you want.
There are several ways to do this. The first step is using the required attribute in your input elements:
<input type="text" name="username" required>
This will force the user to at least put something inside the input element. Then there's Javascript or jQuery for client side validation. You can create a custom event handler to catch the form submit and validate the input like so:
document.getElementById("your_form_id_here").addEventListener("submit", function(e){
// Your Javascript validation code here, for example:
var x = document.forms["your_form_id_here"]["username"].value;
if (x == "") {
alert("Username must be filled out");
e.preventDefault();
}
});
You can also put the form handler on the same file as the form and display the errors / values in case something goes wrong. For example:
<?php
if(!empty($_POST['submit'])){
$error = false;
if($_POST['username'] === ''){
$usernameEmpty = 'The username was empty. Please enter a username!';
$error = true;
}
if(!$error){
// No errors found so proceed with the registration
}
}
?>
<form id="myForm" method="post" action="" accept-charset="utf-8">
<?php if(!empty($usernameEmpty)){ echo $usernameEmpty . '<br/>'; } ?>
Username: <input type="text" name="username" value="<?php if(!empty($_POST['username'])){ echo $_POST['username']; } ?>"/>
<input type="submit" name="submit" value="Register"/>
</form>
Lastly there's of course Ajax which will allow you to send the form towards PHP without reloading your page. You could have PHP send the errors back and use Javascript to show the errors inside the DOM.
without ajax you will need ro lead your page with some conditional logic. This will look and see if any fields are filled in and fill them in again, along with setting any error messages to return to the user.
something like:
<?php
//example fields
$username = '';
$field2 = '';
$field3 = '';
if(isset($errorToShow)){
// echo your error message here
}
if($_POST["submit"]){
foreach($_POST as $k=>$v){
$$k = $v;
}
}
// your form can be here.
of course there are other considerations and ajax is a better solution, but this type of thing can work just fine.
You may use ajax
Or if you don't know ajax
You can put all your code in one page and call $_POST indexes into the value of every input.
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_POST['usename'];?>"/>
Or you may use "PHP $_SESSION"
Just store $_POST into $_SESSION
then call it from the html page
for ex.
<input type="text" name="username" maxlength="25" value="<?=$_SESSION['usename'];?>"/>
And the same idea for errors.
Well, brothers, I'm having a problem with the appearance of notices concerning the form validation. I associate the problem to a few issues on the php code like arrays defined by the variables $errors and $data. I really didn't understand the usage of them. Or maybe it's related to somewhere in the jQuery code.
These codes were based on a website tutorial I've found on the internet. Also, I have no experience in the Ajax and jQuery arenas. Maybe you can solve this simple issue. I even appended the screen captures of the sign up page along with the next page which processes the php connection with database.
This is the sign up page called join_form.php
This is the processing page called register2.php
This is html code:
<html>
<head>
<title>
This is the form page
</title>
</head>
<body>
<center>
<br>
<br>
<img src="images/quintz.png" width="156" height="44" alt=""/>
<br>
<br>
Register now
<br>
<br>
<div id="bugado">
<form id="ajax_form" method="post" action="register2.php">
<div id="usertype-group" class="form-group">
<label for="usertype">
You're a
</label>
<select name="usertype" class="form-control">
<option value="native speaker">
Native speaker
</option>
<option value="non-native speaker">
Non-native speaker
</option>
</select>
<br>
<!-- errors will go here -->
</div>
<div id="username-group" class="form-group">
<label for="username">
Create username:
</label>
<input name="username" type="text" maxlength="30" class="form-control" placeholder="Username">
<br>
</div>
<div id="email-group" class="form-group">
<label for="email">
Email:
</label>
<input name="email" type="text" maxlength="50" class="form-control" placeholder="Email">
<br>
<!-- errors will go here -->
</div>
<div id="password-group" class="form-group">
<label for="password">
Create password:
</label>
<input type="password" name="password" class="form-control" placeholder="Password">
<br>
</div>
<label>
Confirm password:
</label>
<input type="password" name="confirm_password" class="form-control" placeholder="Password again">
<br>
<button type="submit" name="submit" class="btn btn-success">
Submit
</button>
<span class="fa fa-arrow-right">
</span>
<br>
<input name="reset" type="reset" value="Reset">
</form>
</div>
</center>
</body>
</html>
This is the jQuery code:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.js"></script>
<script language="javascript">
$(document).ready(function() {
// process the form
$('#ajax_form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'usertype' : $('select[name="usertype"]').val(),
'username' : $('input[name="username"]').val(),
'email' : $('input[name="email"]').val(),
'password' : $('input[name="password"]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : $(form).attr('action'), // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for usertype ---------------
if (data.errors.usertype) {
$('#usertype-group').addClass('has-error'); // add the error class to show red select
$('#usertype-group').append('<div class="help-block">' + data.errors.usertype + '</div>'); // add the actual error message under our select
}
// handle errors for username ---------------
if (data.errors.username) {
$('#username-group').addClass('has-error'); // add the error class to show red input
$('#username-group').append('<div class="help-block">' + data.errors.username + '</div>'); // add the actual error message under our input
}
// handle errors for email ---------------
if (data.errors.email) {
$('#email-group').addClass('has-error'); // add the error class to show red input
$('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input
}
// handle errors for superhero alias ---------------
if (data.errors.password) {
$('#password-group').addClass('has-error'); // add the error class to show red input
$('#password-group').append('<div class="help-block">' + data.errors.password + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#ajax_form').append('<div class="alert alert-success">' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
alert('success'); // for now we'll just alert the user
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
And this is the php code:
<?php
include 'db.php';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
//Searching for identical usernames
$search = mysql_query("SELECT * FROM natspeaker WHERE username = '".$_POST['username']."'");
$count = mysql_num_rows($search);
$search2 = mysql_query("SELECT * FROM nonnatspeaker WHERE username = '".$_POST['username']."'");
$count2 = mysql_num_rows($search2);
//Searching for identical emails
$search3 = mysql_query("SELECT * FROM natspeaker WHERE email = '".$_POST['email']."'");
$count3 = mysql_num_rows($search3);
$search4 = mysql_query("SELECT * FROM nonnatspeaker WHERE email = '".$_POST['email']."'");
$count4 = mysql_num_rows($search4);
//if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
if(isset($_POST)){
//USERTYPE
if(empty($_POST['usertype'])) {
$errors['usertype'] = "Please select if you are a native or a non-native speaker.<br>";
}
//USERNAME
if (empty($_POST['username'])) {
$errors['username'] = "Username is missing<br>";
}else{//this "else" can be deleted
/*this can be deleted in case of trouble*/if ( $count == 1 OR $count2 == 1) {
$errors['username'] .= "Username already exists in our database. Choose another one<br>";
}
}//this bracket can be deleted.
//EMAIL
if (empty($_POST['email'])) {
$errors['email'] = "Email is missing<br>";
}else{//this "else" can be deleted
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $_POST['email'])) {
$errors['email'] = "Invalid email<br>";
}
if ( $count3 == 1 OR $count4 == 1) {
$errors['email'] = "Email already exists in our database. It seems you have an account yet.<br>";
}
}//this bracket can be deleted.
//PASSWORD
if (empty($_POST['password'])) {
$errors['password'] = "Password is missing.<br>";
}else{//this "else" can be deleted
if (strlen($_POST['password']) < 6) {
$errors['password'] = "Password too short<br>";
}
}//this bracket can be deleted.
// return a response ===========================================================
// if there are any errors in our errors array, return a success boolean of false
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
//if(count($_SESSION['errors']) > 0){
//This is for ajax requests:
if( isset( $_SERVER['REQUEST_METHOD'] ) && $_SERVER['REQUEST_METHOD']=='POST' ) {
//if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])== 'xmlhttprequest') {//something is wrong with this
header('Content-type: application/json');
echo "Ajax request is working.";
echo json_encode($data);//now this iss working
exit;
}
//This is when Javascript is turned off:
echo "<br><br><br><center><div style=\"font-size:50;\">something is wrong or your Javascript is turned off. Ajax request is not working</div></center><br><br>";//delete
echo $data;//delete
//foreach($_SESSION['errors'] as $key => $value){
//echo "<li>" . $value . "</li>";
//}
//echo "</ul>";exit;
}else{
// if there are no errors process our form, then return a message
// DO ALL YOUR FORM PROCESSING HERE
// THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER)
if ( $_POST['usertype'] == "native speaker") {
$register = mysql_query("INSERT INTO natspeaker(username, email, password, time1, usertype)
VALUES ('".$_POST['username']."','".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
}elseif ( $_POST['usertype'] == "non-native speaker"){
$register = mysql_query("INSERT INTO nonnatspeaker(username, email, password, time1, usertype)
VALUES ('".$_POST['username']."', '".$_POST['email']."', '".$_POST['password']."', now(), '".$_POST['usertype']."')") or die (mysql_error());
}
// Let's mail the user!
$subject = "Your Membership at Quintz!";
$message = "Hi, ".$_POST['username'].",
Thank you for registering at our website, http://www.quintz.club!
You have registered as a ".$_POST['usertype'].".
You are two steps away from logging in and accessing our exclusive members area.
To activate your membership, please click here: http://www.quintz.club/activate.php
Once you activate your membership, you will be able to login.
And please do not forget to complete your profile.
Thanks!
The Webmaster
This is an automated response, please do not reply!";
mail($_POST['email'], $subject, $message, "From: Quintz Webmaster<support#quintz.club>\nX-Mailer: PHP/" . phpversion());
// show a message of success and provide a true success variable
$data['success'] = true;
$data['message'] = 'Your account has been created successfully. Go to your email address and activate your account.';
echo "successful register!";//delete
}
}
//}
// return all our data to an AJAX call
//this works
//echo json_encode($data);//delete
?>
In sum, I just want to hinder the user from registering with a username that already exists in the database, or with an invalid email, or even missing information (blank fields), and just return those red notices in the same page join_form.php. The user can only go to the register2.php, if all information are approved to be passed to the database and finally exhibits the message "Successful register!" on this page and sends an email to the user. Just that!
I think you need to go back to the beginning. Your HTML is clearly not on par and your PHP code is.. aged..
Go through what your code is doing, start with HTML, then do the form using jQuery where the output is just either true or the ID of the form field that failed, or something like it.
Just a few quick things;
title goes inside head, not above it
mysql_query is outdated, try using mysqli_query or the OOP variant of that
Do counts when necessary, if the entire form is empty there's no reason to bug the mysql server
Using OOP mysqli, you could just do $s = $mysqli->query('SELECT [..]'); and then if($s->num_rows > 0) instead of making a new variable of the count, using that same way to verify a user does exist for logging in and then just using $r = $s->fetch_assoc() to get the user's details.
Instead of grabbing the values, try writing them all to an array using $('#form').serialize() and then mosting that
In short, go back to the beginning, start over from scratch and use an updated tutorial.
Normally when we submit form in php and show errors then the errors are posted in other page.
Now my question is.
If we want to show the errors on same page mean on the form page, then how to do it?
I used session for that and found it better then other process but when I want to show all session variable at once then it will not show, why?
My code is:
if(isset($_POST) && count($_POST)>0) {
$user =test_input($_POST['user']);
$pass = test_input($_POST['pass']);
$securepassword=hash('sha512', $pass);
if(empty($user)&&empty($pass))
{
echo 'fill every field';
}
else if(empty($user)||empty($pass))
{
echo 'fill both the field';
}
else
{
$sSQL = "SELECT * FROM signup WHERE Username ='".$user."' AND Password = '".$securepassword."'";
$result = mysql_query($sSQL) or die(mysql_error());
$row=mysql_num_rows($result);
if($row==1)
{
// Set username session variable
$_SESSION['user'] = $user;
// Jump to secured page
header('location:index.php');
}
else
{
header('location:signin.php');
}
}
}
You better use JavaScript for validating the form. Lets say this is your HTML code.
<form method="post" name="loginForm" action="abc.php">
<input type="text" name="user">
<input type="password" name="pass">
</form>
Now, let’s add validate this form before you POST to abc.php:
<form method="post" name="loginForm" action="abc.php" onsubmit="return validater()">
<input type="text" name="user">
<input type="password" name="pass">
</form>
And the JavaScript is:
function validater() {
var a= document.forms["loginForm"]["user"].value;
if (a==null || a=="") {
alert("Fill out the username");
return false;
}
var b= document.forms["loginForm"]["pass"].value;
if (b==null || b=="") {
alert("Enter your password");
return false;
}
}
Logic is simple you can put the php code and html code on the same page. In the following order.
Put your php validation code.
Put your error code to show errors above the form.
Put your html code to show the form fields on the page.
There is no need of session to show errors to the user.
I have two input fields and whenever I open my page, it displays errors since at the start user has not entered any input to any of the field (& the errors are displayed because the user input is used in sql queries to retrieve data).
I just want to display those two forms at start of the page not the errors.
Both inputs are required to execute the Compare button. If user has not entered either one of the inputs it should not send request to php for scripting.
I mean the Compare button should send request only if both inputs are filled otherwise it should give a message to user to Type the required fields.
How to do this?
$trimUser= trim ($_POST['name']);
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
& here is my form:
<form action="index.php" method="POST">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
You have to use java script or jQuery for validate both fields are not empty. For Example..
<form action="index.php" method="POST" onsubmit="return validate()">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/>
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
</form>
<script type="text/javascript">
function validate(){
var field1 = document.getElementById('field').value;
var field2 = document.getElementById('field2').value;
if(field1 != '' && field2 != '' ){
return true;
} else{
alert('Type the required fields');
return false;
}
}
</script>
Here if Both fields are not empty then it will be allow to submit form. And In PHP script Add
if(isset($_POST) && !empty($_POST)){
//code comes here
}
I hope it will be helpful for you.
thanks
You can add a check to verify if the request is a post request :
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Place your error checking code here
}
Ehs4n is right, but I would be more specific and do something like :
if(!empty($_POST['compare'])) {
#validation
}
Your button code would have to be changed to :
<button name="compare" value="1" class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
There are two reasons I would do this:
Using !empty() makes sure you don't get an error when $_POST['compare'] is empty
Checking $_POST['compare'] instead of just $_POST makes sure errors are only shown if someone clicks the button.
This last point is key because if you have multiple forms on the page or you happen to set a $_POST variable elsewhere you would still be showing errors.
Use the if condition with isset($_POST) before loading the post.i.e.,
if (isset($_POST)) {
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
I simply got rid all of all the errors by adding this error_reporting(E_ERROR | E_PARSE); at the start of my code.
However if anyone want to check display validation error messages , one can do easily by what others have mentioned . i.e By using if($_Post).
Anyway ,Thank you everyone for the help.
Add if clause like
if($_POST) {
...your validation code
}
Think of redirecting people AFTER the error to the same page they were:
echo '<script>location.href=\'example.php\'</script>';
I have an email form that checks three fields, name, valid email and comments. But the way it's set up now, since name and comments are in one function it first checks name and comments even if email is not valid, how can I re-write it so it checks the fields in order. Also, I would like to re-display the fields that have no errors, so the user doesn't have to type again. Please help. Thanks
<?php
$myemail = "comments#myemail.com";
$yourname = check_input($_POST['yourname'], "Enter your name!");
$email = check_input($_POST['email']);
$phone = check_input($_POST['phone']);
$subject = check_input($_POST['subject']);
$comments = check_input($_POST['comments'], "Write your comments!");
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Enter a valid E-mail address!");
}
exit();
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<!doctype html>
<html>
<body>
<form action="myform.php" method="post">
<p style="color: red;"><b>Please correct the following error:</b><br />
<?php echo $myError; ?></p>
<p>Name: <input type="text" name="yourname" /></P>
<P>Email: <input type="text" name="email" /></p>
<P>Phone: <input type="text" name="phone" /></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
exit();
}
?>
First off, I would suggest you validate ALL of the fields at once, and display all appropriate error messages on the form. The primary reason is that it can be bad user experience if they have to submit your form a whole bunch of times because they have to address one error at a time. I'd rather correct my email address, password, comments, and selection in one try instead of fixing one at a time just to reveal what the next error is.
That said, here are some pointers on validating the form like you want. This is typically how I approach a form doing what you want to do. This assumes your form HTML and form processor (PHP) are together in the same file (which is what you have now). You can split the two, but the methods for doing that can be a bit different.
Have one function or code block that outputs the form and is aware of your error messages and has access to the previous form input (if any). Typically, this can be left outside of a function and can be the last block of code in your PHP script.
Set up an array for error messages (e.g. $errors = array()). When this array is empty, you know there were no errors with the submission
Check to see if the form was submitted near the top of your script before the form is output.
If the form was submitted, validate each field one at a time, if a field contained an error, add the error message to the $errors array (e.g. $errors['password'] = 'Passwords must be at least 8 characters long';)
To re-populate the form inputs with the previous values, you have to store the entered values somewhere (you can either just use the $_POST array, or sanitize and assign the $_POST values to individual variables or an array.
Once all the processing is done, you can check for any errors to decide whether the form can be processed at this point, or needs new input from the user.
To do this, I typically do something like if (sizeof($errors) > 0) { // show messages } else { // process form }
If you are re-displaying the form, you simply need to add a value="" attribute to each form element and echo the value that was submitted by the user. It is very important to escape the output using htmlspecialchars() or similar functions
With those things in place, here is some re-work of your form to do that:
<?php
$myemail = "comments#myemail.com";
$errors = array();
$values = array();
$errmsg = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
foreach($_POST as $key => $value) {
$values[$key] = trim(stripslashes($value)); // basic input filter
}
if (check_input($values['yourname']) == false) {
$errors['yourname'] = 'Enter your name!';
}
if (check_input($values['email']) == false) {
$errors['email'] = 'Please enter your email address.';
} else if (!preg_match('/([\w\-]+\#[\w\-]+\.[\w\-]+)/', $values['email'])) {
$errors['email'] = 'Invalid email address format.';
}
if (check_input($values['comments']) == false) {
$errors['comments'] = 'Write your comments!';
}
if (sizeof($errors) == 0) {
// you can process your for here and redirect or show a success message
$values = array(); // empty values array
echo "Form was OK! Good to process...<br />";
} else {
// one or more errors
foreach($errors as $error) {
$errmsg .= $error . '<br />';
}
}
}
function check_input($input) {
if (strlen($input) == 0) {
return false;
} else {
// TODO: other checks?
return true;
}
}
?>
<!doctype html>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<?php if ($errmsg != ''): ?>
<p style="color: red;"><b>Please correct the following errors:</b><br />
<?php echo $errmsg; ?>
</p>
<?php endif; ?>
<p>Name: <input type="text" name="yourname" value="<?php echo htmlspecialchars(#$values['yourname']) ?>" /></P>
<P>Email: <input type="text" name="email" value="<?php echo htmlspecialchars(#$values['email']) ?>" /></p>
<P>Phone: <input type="text" name="phone" value="<?php echo htmlspecialchars(#$values['phone']) ?>"/></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" value="<?php echo htmlspecialchars(#$values['subject']) ?>" /></p>
<p>Comments:<br />
<textarea name="comments" rows="10" cols="50" style="width: 100%;"><?php echo htmlspecialchars(#$values['comments']) ?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
I have a more advanced example which you can see here that may give you some guidance as well.
Hope that helps.
The simplest option is to use a form validation library. PHP's filter extension, for example, offers validation and sanitization for some types, though it's not a complete solution.
If you insist on implementing it yourself, one issue you'll have to consider is what counts as the order: the order of the elements in the form or the order of the user input in $_POST. On most browsers, these should be the same, but there's no standard that enforces this. If you want to go off of form order, you'll need to define the form structure in one place, and use that information to do things like generating or validating the form (a consequence of the Don't Repeat Yourself (DRY) principle). Iterating over the appropriate structure will give you the order you desire: looping over the form gives you form order, whereas looping over $_POST gives you user input order.
It looks like you want to more than simply validate the data; you also want to prepare it for use, a process called "sanitization".
When it comes to sanitization, define different kinds of sanitizers, rather than a single check_input function. Specific sanitizers could be functions, or objects with an __invoke method. Create a map of form fields to sanitizers (for example, an array of input name to sanitizer callbacks). The order of the elements in the mapping sets the order of the sanitization; if you use a single structure to define the form information, the display order and sanitization order will thus be the same.
Here's a very broad outline:
# $fields could be form structure or user input
foreach ($fields as $name => $data) {
# sanitize dispatches to the appropriate sanitizer for the given field name
$form->sanitize($name, $data);
# or:
//sanitize($name, $data);
# or however you choose to structure your sanitization dispatch mechanism
}
As for setting an input's value to the user-supplied data, simply output the element value when outputting the element. As with all user input (really, all formatted output), properly escape the data when outputting it. For HTML attributes, this means using (e.g.) htmlspecialchars. Note you should only escape outgoing data. This means your sanitization functions shouldn't call htmlspecialchars.
You can improve usability by placing each error next to the corresponding input, adding an "error" class to the element and styling the "error" class to make it stand out. Improve accessibility by wrapping <label> elements around the label text.
Use this structure of script:
<?php
$errors = array();
if (isset($_POST['send'])) {
// check data validity
if (!mailValid($_POST['email']))
$errors[] = 'Mail is not valid';
...
// send data by email
if (!$errors) {
// send mail and redirect
}
}
?>
<html>
...
<?php
if ($errors) {
// display errors
foreach ($errors as $error) {
echo "$error<br />";
}
}
?>
<form ...>
...
Email: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '' ?>" />
...
</form>
...
</html>
You could always do it like this, using filter_var and in_array checks:
<?php
$myemail = "comments#myemail.com";
//Pre made errors array
$errors=array('name'=>'Enter Your name',
'email'=>'Please enter valid email',
'phone'=>'Please enter valid phone number',
'subject'=>'Please enter valid subject, more then 10 chars',
'comment'=>'Please enter valid comment, more then 10 chars');
//Allowed post params and its validation type
$types = array('name'=>'string',
'email'=>'email',
'phone'=>'phone',
'subject'=>'string',
'comment'=>'string');
//A simple validation function using filter_var
function validate($value,$type){
switch ($type){
case "email":
return ((filter_var($value, FILTER_VALIDATE_EMAIL))?true:false);
break;
case "phone":
return ((preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $value))?true:false);
break;
case "string":
return ((strlen($value) >=10 )?true:false);
break;
default:
return false;
break;
}
}
//If forms been posted
if(!empty($_POST) && $_SERVER['REQUEST_METHOD'] == 'POST'){
//Assign true, if all is good then this will still be true
$cont=true;
$error=array();
foreach($_POST as $key=>$value){
//if key is in $types array
if(in_array($key,$types)){
//If validation true
if(validate($value, $types[$key])==true){
$$key=filter_var($value, FILTER_SANITIZE_STRING);
}else{
//Validation failed assign error and swithc cont to false
$error[$key]=$errors[$key];
$cont=false;
}
}
}
}
if($cont==true && empty($error)){
//Send mail / do insert ect
}else{
//Default to form
?>
<!doctype html>
<html>
<body>
<form action="" method="post">
<p>Name: <input type="text" name="name" value="<?=#htmlentities($name);?>"/> <?=#$error['name'];?></P>
<P>Email: <input type="text" name="email" value="<?=#htmlentities($email);?>" /> <?=#$error['email'];?></p>
<P>Phone: <input type="text" name="phone" value="<?=#htmlentities($phone);?>"/> <?=#$error['phone'];?></p><br />
<P>Subject: <input type="text" style="width:75%;" name="subject" /> <?=#$error['subject'];?></p>
<p>Comments: <?=#$error['comment'];?><br />
<textarea name="comment" rows="10" cols="50" style="width: 100%;"><?=#htmlentities($comment);?></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
<?php
}?>