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);
 ?>
Jon Tan
  • 1,461
  • 3
  • 17
  • 33
Lambo
  • 79
  • 2
  • 11

7 Answers7

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
   );
}
codesniffer
  • 1,033
  • 9
  • 22
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.

Jon Tan
  • 1,461
  • 3
  • 17
  • 33
  • 1
    Thanks for sharing the diff between isset and empty. I will work on my code – Lambo Oct 10 '15 at 13:13
  • 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 - http://stackoverflow.com/questions/4559925/why-check-both-isset-and-empty – Jon Tan Oct 11 '15 at 14:45
  • See my post for why *not* to use the empty function for such validation. – codesniffer Oct 28 '15 at 02:08
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);
 ?>
Akshay
  • 2,244
  • 3
  • 15
  • 34
0

check like this:

if(!isset($_POST["username"]) && $_POST["username"]!="")
Karim Pazoki
  • 951
  • 1
  • 13
  • 34
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'])) 
Arif
  • 308
  • 2
  • 8
-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 ;)

NeoTrix
  • 124
  • 8
  • 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. – John Conde Oct 10 '15 at 12:46
  • @Neo Yes I need to unset but let me finish this error first. Thanks alot – Lambo Oct 10 '15 at 13:15
  • @Neo used atlast in Login.php .Everything Fixed now – Lambo Oct 10 '15 at 13:36
  • @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. – NeoTrix Oct 10 '15 at 13:43
-1
if(isset($_POST['field_name']))
{
$field_name=$_POST['field_name']

}else
{
 unset($_POST['field_name'])
}
Ankit Verma
  • 136
  • 4
  • 10