0

I am learning the PHP and I need to know about the server side error and what is the best way to secure the database. I referred the google and got some valuable information and I applied to my code. Please check my code and assist me more to understand the PHP.

I have a registration form with client-side validation and server-side validation.

There is no issue with client-side validation even server-side validation is also working in case someone hides the javascript from the browser.

My concern is, I used session for server-side validation to display the error message.

1) Is it a right way to use to display the server side error message from one page to another? or any other best way to display the error message?

2) While displaying server side validation, Fields are showing blank. Any help on this issue?

3) I am using prepared statement. I tried $name=$conn->real_escape_string(strip_tags(htmlspecialchars(stripslashes(trim($_POST['name']))))); Is it a good way to use for secure the data?

Would you help me out in this issue?

Register.php

<?php
session_start();
/*server side checking and error display*/
$name_error="";
$email_error=""; 
$password_error="" ;
$mobilenumber_error="";

$name_error=isset($_SESSION['name_error'])?$_SESSION['name_error']:'';
$email_error=isset($_SESSION['email_error'])?$_SESSION['email_error']:'';
$password_error=isset($_SESSION['password_error'])?$_SESSION['password_error']:'';
$mobilenumber_error=isset($_SESSION['mobilenumber_error'])?$_SESSION['mobilenumber_error']:'';

?>
<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style type="text/css">
        form{width: 400px;margin: auto;}
    </style>

</head>
<body>
     <form action="process.php?key=register" method="post" name="register" autocomplete="off">
          <div class="form-group">
              <label for="name">Name</label>
              <input type="text" class="form-control" id="name" name="name">
              <span class="error"><?php echo $name_error;?></span>
            </div>

            <div class="form-group">
              <label for="email">Enter Email</label>
              <input type="email" class="form-control" id="email" name="email" >
              <span class="error"><?php echo $email_error;?></span>
            </div>

            <div class="form-group">
              <label for="pwd">Password</label>
              <input type="password" class="form-control" id="password" name="password">
                   <span class="error"><?php echo $password_error;?></span>
            </div>

            <div class="form-group">
              <label>Mobile number</label>
              <input type="text" class="form-control" id="mobilenumber" name="mobilenumber">
              <span class="error"><?php echo $mobilenumber_error;?></span>
            </div>


              <div class="form-group">
              <input type="submit" class="btn-reg btn-default" value="Register">
              </div>
    </form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>
<script src="validation.js"></script>
</body>
</html>

Process.php

<?php
ob_start();
session_start();
include('../db/connection.php');
date_default_timezone_set('Asia/Kolkata');
$date_of_added= date('d-m-Y H:i:s');//current date

switch($_GET['key']) {
case 'register':register($conn);break;
default : redirect('index.php');
}

/*register code*/

function register($conn)
{

  global $date_of_added;
  // $products_image=$newfilename;
  $name=$conn->real_escape_string(strip_tags(htmlspecialchars(stripslashes(trim($_POST['name'])))));
  $email=$conn->real_escape_string(strip_tags(htmlspecialchars(stripslashes(trim($_POST['email'])))));
  $password=$conn->real_escape_string(strip_tags(htmlspecialchars(stripslashes(trim($_POST['password'])))));
  $mobilenumber=$conn->real_escape_string(strip_tags(htmlspecialchars(stripslashes(trim($_POST['mobilenumber'])))));

  /*server side validation*/
  $_SESSION['name_error']="";
  $_SESSION['email_error']="";
  $_SESSION['password_error']="";
  $_SESSION['confirmpassword_error']="";

if (empty($name)) {
      $_SESSION['name_error']="Name is empty";
      header('location:register');
  }

elseif(strlen($name) >3) {
        $_SESSION['name_error']="Please enter minimum 3 character";
        header('location:register');
}

elseif(empty($email)) {
      $_SESSION['email_error']="Email field is empty";
      header('location:register');
  }
elseif(!preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
        $_SESSION['email_error']="Invalid email format"; 
        header('location:register');
  }

elseif(empty($password)) {
      $_SESSION['password_error']="Password field is empty";
      header('location:register');
  }

elseif(empty($mobilenumber))
 {
  $_SESSION['contact_mobile_error'] = "Enter Mobile NO !";
  header('location:register');
 }
 elseif(!is_numeric($mobilenumber))
 {
  $_SESSION['contact_mobile_error'] = "Numbers only !";
  header('location:register');
 }
 elseif(strlen($mobilenumber)!=10)
 {
  $_SESSION['contact_mobile_error'] = "10 characters only !";
  header('location:register');
 }
  else{
  $password_hash =password_hash($password,PASSWORD_DEFAULT,['cost' => 12]);
  // prepare and bind
  $sql="INSERT INTO test (name, email, password, mobileno, date_of_added) VALUES (?, ?, ?, ?, ?)";
  $stmt = $conn->prepare($sql);
  $stmt->bind_param("sssss", $name, $email, $password_hash, $mobilenumber, $date_of_added);
  $stmt->execute();
  $stmt->close();
  }
 header('location:register');
  $conn->close();
}

Validation.js(Client side validation)

// When the browser is ready...
  $(function() {
/*password alphanumeric set*/
   $.validator.addMethod("pwcheckallowedchars", function (value) {
        return /^[a-zA-Z0-9!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]+$/.test(value) // has only allowed chars letter
    }, "The password contains non-admitted characters");

    $.validator.addMethod("pwcheckspechars", function (value) {
        return /[!@#$%^&*()_=\[\]{};':"\\|,.<>\/?+-]/.test(value)
    }, "The password must contain at least one special character");

  $.validator.addMethod("pwcheckconsecchars", function (value) {
        return ! (/(.)\1\1/.test(value)) // does not contain 3 consecutive identical chars
    }, "The password must not contain 3 consecutive identical characters");

    $.validator.addMethod("pwchecklowercase", function (value) {
        return /[a-z]/.test(value) // has a lowercase letter
    }, "The password must contain at least one lowercase letter");

    $.validator.addMethod("pwcheckrepeatnum", function (value) {
        return /\d{2}/.test(value) // has a lowercase letter
    }, "The password must contain at least one lowercase letter");

    $.validator.addMethod("pwcheckuppercase", function (value) {
        return /[A-Z]/.test(value) // has an uppercase letter
    }, "The password must contain at least one uppercase letter");

    $.validator.addMethod("pwchecknumber", function (value) {
        return /\d/.test(value) // has a digit
    }, "The password must contain at least one number");

  $("form[name='register']").validate({
        // Specify the validation rules
        rules: {

           name:{
                 required: true,
                 minlength:3,
                maxlength:50
           },

           email: {
                required: true,
                 email:true
            },

           password: {
                required: true,
                pwchecklowercase: true,
                pwcheckuppercase: true,
                pwchecknumber: true,
                pwcheckconsecchars: true,
                pwcheckspechars: true,
                pwcheckallowedchars: true,
                minlength:5,
                 maxlength: 20
            },

            mobilenumber: {
                required: true,
                number:true,
                minlength:10,
                maxlength: 10

            }

               },
         submitHandler: function(form) {
         form.submit();
         }

    });
  });
user9437856
  • 2,360
  • 2
  • 33
  • 92

1 Answers1

0

I think your question has less to do with jquery than wit good old fashioned server side php.

To answer your questions (as good as I can): 1) Is it a right way to use to display the server side error message from one page to another? or any other best way to display the error message?

I would think becuase this is a working solution it is a good solution, but I would not have chosen this way. Why not put the code from register.php and process.php in one file, so you don't have to use the sessions and redirect?

2) While displaying server side validation, Fields are showing blank. Any help on this issue?

To achieve this in your code you would need to fill sessions variables for the inputs in process.php:

$_SESSION['name']=$name;

You can then use this in register.php like this:

<input type="text" class="form-control" id="name" name="name" value="<?=$_SESSION['name']?>">

3) I am using prepared statement. I tried $name=$conn->real_escape_string(strip_tags(htmlspecialchars(stripslashes(trim($_POST['name']))))); Is it a good way to use for secure the data?

I would not know. I would think it is as good as any method.

Hans Dash
  • 761
  • 4
  • 18