- SPLessons

PHP Secure Login

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

PHP Secure Login

 PHP Secure Login 


 

Problem in logging into your site. Follow the below few steps to how you login into your site securely.

Description :

PHP secure login with prepare and execute statements.

 

Step1 :

Add the below table in your database.
1. users

Step2 :

Create a PHP file and name it is as ‘db.php’. Add below code in that file.

<?php 

    // These variables define the connection information for your MySQL database
    $username = "root";
    $password = "";
    $host = "localhost";
    $dbname = "php_secure_login_db"; 

    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 

    try
    {
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
    }
    catch(PDOException $ex)
    {
        die("Failed to connect to the database: " . $ex->getMessage());
    } 

    // an error.  This allows us to use try/catch blocks to trap database errors.
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     

    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);      

    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
    {
        function undo_magic_quotes_gpc(&$array)
        {
            foreach($array as &$value)
            {
                if(is_array($value))
                {
                    undo_magic_quotes_gpc($value);
                }
                else
                {
                    $value = stripslashes($value);
                }
            }
        } 

        undo_magic_quotes_gpc($_POST);
        undo_magic_quotes_gpc($_GET);
        undo_magic_quotes_gpc($_COOKIE);
    } 

    // This tells the web browser that your content is encoded using UTF-8
    // and that it should submit content back to you using UTF-8
    header('Content-Type: text/html; charset=utf-8');
    session_start();

Step3 :

Create a page with name of ‘create_new_user.php’ and add the below code in that file. This will create a user in your ‘user’ table with below values that your provided.


<?php
        $Name="Madhu";
	    $email="madhureddy.kunta@gmail.com";
	    $User_name="Madhu522";
	    $Password="splessons";

require "db.php";
 $query = " INSERT INTO users (Name, User_name, Password, salt, email, Created_date, Last_modified
            ) VALUES (
			    :Name,
                :User_name,
                :Password,
                :salt,
                :email,
				:Created_date,
				:Last_modified
            )"; 

        $salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));          

        $Password = hash('sha256', $Password . $salt);          

        for($round = 0; $round < 65536; $round++)
        {
            $Password = hash('sha256', $Password . $salt);
        }
        $query_params = array(
		    ':Name' => $Name,
            ':User_name' => $User_name,
            ':Password' => $Password,
            ':salt' => $salt,
            ':email' => $email,
			':Created_date'=>date("Y-m-d H:i:s"),
			':Last_modified'=>date("Y-m-d H:i:s")
        ); 

        try
        {
            // Execute the query to create the user
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        } 

        // This redirects the user back to the login page after they register
        header("Location: index.php"); 

        // will be sent to the user if you do not die or exit.
        die("Redirecting to index.php"); 

Step4 :

Now you just created a user to your application. Create a page ‘index.php’
Add below code in that file to create the simple login form


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Secure Login</title>

<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css"     /> <!-- to apply styles to your form this is not mandatory-->

</head>
<body>

<div style="margin:10%;margin-left:20%;">

<h3 style="margin-left:10%">Login to Your Site</h3>

<form name="login-form" class="form-horizontal" action="user_authenticate.php" method="post" role="form">

  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">User Name</label>
    <div class="col-sm-4">
      <input type="text" class="form-control" id="inputEmail3" name="User_name">
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-4">
      <input type="password" class="form-control" id="inputPassword3" name="Password" >
    </div>
  </div>

  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Sign in</button>

      <?php  if(isset($_REQUEST["message"])) {
		echo  "<span style='color:#ff0000;margin-left:10px;'>". $_REQUEST["message"]."</span>";
	}?>

    </div>
  </div>

</form>
</div>
</body>
</html>

Step5 :

Next you need to create ‘user_authenticate.php’ to validate the logged in user. Add below code in that file. 

<?php 

    // First we execute our common code to connection to the database and start the session
    require("db.php");
    $submitted_username = '';
    // If it has, then the login code is run, otherwise the form is displayed
    if(!empty($_POST))
    { 

        // This query retreives the user's information from the database using
        // their username.
        $query = "
            SELECT
                Id,
                User_name,
                Password,
                salt,
                email
            FROM users
            WHERE
                User_name = :User_name
        "; 

        // The parameter values
        $query_params = array(
            ':User_name' => $_POST['User_name']
        ); 

        try
        {
            // Execute the query against the database
            $stmt = $db->prepare($query);
            $result = $stmt->execute($query_params);
        }
        catch(PDOException $ex)
        {
            // Note: On a production website, you should not output $ex->getMessage().
            // It may provide an attacker with helpful information about your code.
            die("Failed to run query: " . $ex->getMessage());
        } 

        // This variable tells us whether the user has successfully logged in or not.
        // We initialize it to false, assuming they have not.
        // If we determine that they have entered the right details, then we switch it to true.
        $login_ok = false; 

        // Retrieve the user data from the database.  If $row is false, then the username
        // they entered is not registered.
        $row = $stmt->fetch();
        if($row)
        {
            // Using the password submitted by the user and the salt stored in the database,
            // we now check to see whether the passwords match by hashing the submitted password
            // and comparing it to the hashed version already stored in the database.
            $check_password = hash('sha256', $_POST['Password'] . $row['salt']);
            for($round = 0; $round < 65536; $round++)
            {
                $check_password = hash('sha256', $check_password . $row['salt']);
            } 

            if($check_password === $row['Password'])
            {
                // If they do, then we flip this to true
                $login_ok = true;
            }
        } 

        // If the user logged in successfully, then we send them to the private members-only page
        // Otherwise, we display a login failed message and show the login form again
        if($login_ok)
        { 

            // sensitive values first.
            unset($row['salt']);
            unset($row['Password']); 

            // the user's details.
            $_SESSION['user'] = $row; 

            // Redirect the user to the private members-only page.
            header("Location: Home.php");
            die("Redirecting to: Home.php");
        }
        else
        {
            // Tell the user they failed
            print("Login Failed.");
              header("Location: index.php?message=Username or Password wrong"); 

            $submitted_username = htmlentities($_POST['User_name'], ENT_QUOTES, 'UTF-8');
        }
    } 

?>

Step6 :

If user successfully validate then it will redirect to ‘Home.php’ or else it will redirect into ‘index.php’ with a message ‘User Name or Password wrong’. Add below code in ‘Home.php’


<?php  error_reporting(0);

    // First we execute our common code to connection to the database and start the session
    require("db.php"); 

    // At the top of the page we check to see whether the user is logged in or not
    if(empty($_SESSION['user']))
    {
        // If they are not, we redirect them to the login page.
        header("Location: index.php"); 

        // Remember that this die statement is absolutely critical.  Without it,
        // people can view your members-only content without logging in.
        die("Redirecting to index.php");
    } 

    ?>

 

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Home-XYZ</title>
      <meta charset="utf-8">  

   </head>
   <body>

    <div style="margin:10%;">

  <h2 align="center">  Your Home Page </h2>
  <h2 align="center"><a href="logout.php">Logout</a> </h3>

    </div>

   </body>
</html>

Step7 :

After successfully logged in if you want logout, you can destroy the session of that particular user by below code. Add below in ‘logout.php’


<?php 

    // First we execute our common code to connection to the database and start the session
    require("db.php"); 

    // We remove the user's data from the session
    unset($_SESSION['user']); 

    // We redirect them to the login page
    header("Location: index.php");
    die("Redirecting to: index.php");
	?>

After logging out it will redirect to ‘index.php’. Now your created simple application PHP secure login.
Note: Create user with ‘create_new_user.php’ and pass the parameters with different values and execute it in your PHP server.