1

I am new to PHP and am trying to do Server Side Form Validation. There are two PHP files Login.php and Form.php. Registration is done in Login.php and Validation in Form.php. The idea is that Form.php will process the form data sent by Login.php

My problem: even if form fields are empty, the variables are still being inserted into the database.

I don't want to insert if its empty. Rather, it has to route back to Login.php with error messages stored as a session variable.

I have checked the Form fields using !isset() and empty in Form.php using an if..else clause. In the if..else clause you can find out if the form fields are empty, and if so, they must go the session variable clause (inside the if condition). Instead, it is going to the else condition and inserting the empty values in variables ('$username','$password','$phone','$mailid','$city') in to the database.

I have read previous questions for similar problem here and even checked Youtube for Server Side Validation. What did I do wrong? Is there a problem with the use of session variables. Kindly assist

Login.php:

<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>

<?php
    session_start();
    $passworderr='';    
    if(isset($_SESSION["passworderr"])) {
        $passworderr=$_SESSION["passworderr"];
    }
?>

 <div id="Outer">
 <div id="left" >
  <form action="/DatabaseDrivenWebpage/Form.php" method="POST"     name="form">
 <p><label>Username</label> <input type="text" name="regusername"    placeholder="Your name"/> </p>
 <p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
 <input type="Submit" value="Login" />
 </form>
 </div>

 <div id="right">
 <form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
 <p>*Username <input required name="username" type="text" /><?php  //echo $usernameerr;?></p>
 <p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p> 
 <p>   *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p>  *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p>    *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
  <input type="Submit" value="Signup" />
</form></div></div></body></html>

Form.php:

<?php

session_start();

   $dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';

$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
 if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}

 if(!isset($_POST["username"])) {
     $_SESSION["usernameerr"]="UserName is required";
 }
 else{
     $username=mysqli_real_escape_string($dbconn,$_POST["username"]);
 }
 if(!isset($_POST["password"])) {
     $_SESSION["passworderr"]="Enter a password";
 }
 else{
     $password=mysqli_real_escape_string($dbconn,$_POST["password"]);
 }
 if(!isset($_POST["phone"])) {
     $_SESSION["phoneerr"]="Phone number is required";
 } 
 else{
     $phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
 }
 if(!isset($_POST["mailid"])) {
     $_SESSION["mailiderr"]="Enter a valid mail id";
 } 
 else{
     $mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
 }
 if(!isset($_POST["city"])) {
     $_SESSION["cityerr"]="Enter your resident city";
 } 
 else{
     $city=mysqli_real_escape_string($dbconn,$_POST["city"]);
 }

 $selected = mysqli_select_db($dbconn,"$dbname")
 or die("Could not select examples".mysqli_error($dbconn));

 if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )
 {
     $res=mysqli_query($dbconn,"Insert into   user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
     if($res)
     {
         header("location:Login.php");
     }
 }
 else
 {
 print "Problem in inserting";
 header("location:Login.php");
 } 

 mysqli_close($dbconn);
 ?>

7 Answers 7

2

There are a bunch of ways to do this. A blank form field is present on the server side with an empty value. So in addition to checking if the variable is set, in your case you want to check if the value is non-empty. One way to do that is to use the strlen function. So an example for you is:

if(!isset($_POST["username"]) || strlen($_POST["username"]) == 0) {

NOTE: Do not use the empty function since the string "0" is considered 'empty'. Read the manual for other such cases.

You may want to consider using a helper function to do the determination. Basically something like this:

function DoesPostFormFieldHaveValue($formFieldName) {
   return(
         isset($_POST[$formFieldName])
      && strlen($_POST[$formFieldName]) > 0
   );
}
Sign up to request clarification or add additional context in comments.

Comments

1

First of all, session_start should always be the first line of the php page you need to use sessions on.

Also, I'm not sure why you are using so many session variables for storing errors. Instead of this, use a single session variable, declare it as array and store all the errors in it.

Here's your updated form :-

<?php
    session_start();
    if((isset($_SESSION['errors']))) //check if we have errors set by the form.php page
    {
        echo "Please fix the following errors";
        foreach($_SESSION['errors'] as $error) //loop through the array
        {
            echo $error;
        }
    }
?>

<!Doctype HTML>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href= "Form.css" />
<script src="Form.js" type="text/javascript"></script>
</head>
<body>



 <div id="Outer">
 <div id="left" >
  <form action="/DatabaseDrivenWebpage/Form.php" method="POST"     name="form">
 <p><label>Username</label> <input type="text" name="regusername"    placeholder="Your name"/> </p>
 <p><label>Password</label> <input type="text" name="regpassword" placeholder="Password"/> </p>
 <input type="Submit" value="Login" />
 </form>
 </div>

 <div id="right">
 <form action="/DatabaseDrivenWebpage/Form.php" method="POST" id="formm">
 <p>*Username <input required name="username" type="text" /><?php  //echo $usernameerr;?></p>
 <p>*Password <input name="password" type="password" /> <?php echo $passworderr;?></p> 
 <p>   *Phone <input name="phone" type="tel" /><?php //echo $phoneerr;?></p>
<p>  *MailId <input name="mailid" type="email" /><?php //echo $mailiderr;?></p>
<p>    *City <input name="city" type="text" /><?php //echo $cityerr;?></p>
  <input type="Submit" value="Signup" />
</form></div></div></body></html>

Backend processing file :-

<?php
session_start();
$_SESSION['errors'] = array(); //declare an array
   $dbservername='localhost';$dbname='mani';$dbusername='root';$dbpassword='';

$dbconn=mysqli_connect($dbservername,$dbusername,$dbpassword);
 if(!$dbconn){
die("Connection failed:". mysqli_connect_error());
}

 if((!isset($_POST["username"])) || (empty($_POST['username']))) {
     $_SESSION["errors"][]="UserName is required"; //push error message to array if $_POST['username'] is empty or is not set
 }
 else{
     $username=mysqli_real_escape_string($dbconn,$_POST["username"]);
 }
 if((!isset($_POST["password"])) || (empty($_POST['password']))) {
     $_SESSION["errors"][]="Enter a password";
 }
 else{
     $password=mysqli_real_escape_string($dbconn,$_POST["password"]);
 }
 if((!isset($_POST["phone"])) || (empty($_POST['phone']))) {
     $_SESSION["errors"][]="Phone number is required";
 } 
 else{
     $phone=mysqli_real_escape_string($dbconn,$_POST["phone"]);
 }
 if((!isset($_POST["mailid"])) || (empty($_POST['mailid']))) {
     $_SESSION["errors"][]="Enter a valid mail id";
 } 
 else{
     $mailid=mysqli_real_escape_string($dbconn,$_POST["mailid"]);
 }
 if((!isset($_POST["city"])) || (empty($_POST['city']))) {
     $_SESSION["errors"][]="Enter your resident city";
 } 
 else{
     $city=mysqli_real_escape_string($dbconn,$_POST["city"]);
 }

 $selected = mysqli_select_db($dbconn,"$dbname")
 or die("Could not select examples".mysqli_error($dbconn));

 if(count($_SESSION['errors']) < 1) //check if the the $_SESSION['errors'] count is less than 1 (0), this means there are no errors.
 {
     $res=mysqli_query($dbconn,"Insert into   user(username,password,phone,mailid,city) values('$username','$password','$phone','$mailid','$city')");
     if($res)
     {
         header("location:Login.php");
     }
 }
 else
 {
 print "Problem in inserting";
 header("location:Login.php");
 } 

 mysqli_close($dbconn);
 ?>

3 Comments

They're using mysqli which is not deprecated.
@JohnConde Oops, I missed the i
See my post for why not to use the empty function for such validation.
1

The thing about isset is that it checks if the variable exists, and therefore allows variables that contain an empty string, like you have. When the current form is submitted without any user input, it is submitting a whole bunch of variables containing empty strings.

Now the solution is to change all your isset() to empty() and that should solve your problem!


[Note] There is no need to use both isset() and empty() like this:

if(!isset($_POST['fieldname']) && !empty($_POST['fieldname']))

because empty() is doing everything that isset() does.

3 Comments

Thanks for sharing the diff between isset and empty. I will work on my code
Maybe my explanation skills left something to be desired, but as to why it is not necessary to use isset() together with !empty, refer to this stackoverflow link - stackoverflow.com/questions/4559925/…
See my post for why not to use the empty function for such validation.
0

check like this:

if(!isset($_POST["username"]) && $_POST["username"]!="")

1 Comment

You should be using empty() instead of checking for an empty string.
0

Your PHP code is checking for isset only, I don't see any empty check. isset will be always true in your case to either of the forms, as the form fields are submitting - just the values are blank. To prevent empty insertions, add a !empty check to your conditions. Your conditional statements should look like this -

if(!isset($_POST['fieldname']) && !empty($_POST['fieldname'])) 

Comments

-1

first of all a little advice. If you want to start a new project, I would advice you learn how to use PDO connection to MySQL Databases, and not MySQLi. As PDO is much better method, and secured (especially when using prepared statements).

Anyway, as I can see you are storing the errors in a multiple $_SESISON variables, but after you are finishing the validation checks, you are not doing a correct if statement.

Instead of doing that: if(isset($_POST["username"]) and isset($_POST["password"]) and isset($_POST["phone"]) and isset($_POST["mailid"]) and isset($_POST["city"]) )

Do something like this: if(!isset($_SESSION['usernameerr']) && !isset($_SESSION['passworderr']) && !isset($_SESSION['phoneerr'] && !isset($_SESSION['mailiderr'] && !isset($_SESSION['cityerr'])))

Should work.

Another think I'm advising is to unset the sessions of the errors, in your case I would do that in the end of the Login.php page. Just in case, so there won't be any problems if you fix the form inputs and submit it again.

Another thing, based on the unset idea. If you will do this, it would be much more cleaner way to change the setting of the error sessions instead of: $_SESSION['cityerr'] to: $_SESSION['errors']['cityerr']

So afterwards, you can clean the specific form error session in one command, like that: unset($_SESSION['errors']);

Hope it helped ;)

4 Comments

Although PDO is generally recommended, MySQLi is just fine. As long as they're not using mysql_* there's no reason to point this out.
@Neo Yes I need to unset but let me finish this error first. Thanks alot
@Neo <?php session_unset(); ?> used atlast in Login.php .Everything Fixed now
@Lambo, don't use session_unset, as you will probably store other things in the session, like login session, or any other things. If you will use session_unset it will delete all the session content, which is not something i would advise on.
-1
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']

}else
{
 unset($_POST['field_name'])
}

3 Comments

This is completely wrong. There is no is_set() in PHP. It's isset() and they are already using that.
ohh ya i made a mistake there please use isset() function
You still get downvoted for telling them to do exactly what they are already doing which obviously is not working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.