Password Hashing in PHP
Functions for hashing password
password_hash() –
Syntax:
1 |
string password_hash(string $password , integer $algo [, array $options ] ) |
string $password – Password provide by user
integer $algo – Password algorithm constant(PASSWORD_DEFAULT and PASSWORD_BCRYPT)
PASSWORD_DEFAULT – uses the BCrypt algorithm to create the hash
PASSWORD_BCRYPT – uses the CRYPT_BLOWFISH algorithm and will return a 60 character string
$options –
$options have two indexes.One is cost and another one is salt.
Cost- Cost is the repetition of algorithm which have default value 10. Which means algorithm will run 10 times to make a strong hash. You can configure your cost value according to your server configuration.
Syntax-
1 2 3 4 5 6 7 8 |
<?php $password=$_POST['password']; $options = array( 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM), 'cost' => 12, ); $hashedpass=password_hash($password, PASSWORD_BCRYPT, $options); ?> |
password_verify()
password_verify() used for checking a password against a password hash, then return a boolean.
1 2 3 4 5 |
if (password_verify($passowrd, $hashedpass)) { echo 'Password is valid!'; } else { echo 'Invalid password.'; } |
Example –
Signup.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 |
<?php //Database Configuration File include('config.php'); //error_reporting(0); if(isset($_POST['signup'])) { //Getting Post Values $fullname=$_POST['fname']; $username=$_POST['username']; $email=$_POST['email']; $mobile=$_POST['mobilenumber']; //Password hashing $password=$_POST['password']; $options = ['cost' => 12]; $hashedpass=password_hash($password, PASSWORD_BCRYPT, $options); // Query for validation of username and email-id $ret="SELECT * FROM userdata where (UserName=:uname || UserEmail=:uemail)"; $queryt = $dbh -> prepare($ret); $queryt->bindParam(':uemail',$email,PDO::PARAM_STR); $queryt->bindParam(':uname',$username,PDO::PARAM_STR); $queryt -> execute(); $results = $queryt -> fetchAll(PDO::FETCH_OBJ); if($queryt -> rowCount() == 0) { // Query for Insertion $sql="INSERT INTO userdata(FullName,UserName,UserEmail,UserMobileNumber,LoginPassword) VALUES(:fname,:uname,:uemail,:umobile,:upassword)"; $query = $dbh->prepare($sql); // Binding Post Values $query->bindParam(':fname',$fullname,PDO::PARAM_STR); $query->bindParam(':uname',$username,PDO::PARAM_STR); $query->bindParam(':uemail',$email,PDO::PARAM_STR); $query->bindParam(':umobile',$mobile,PDO::PARAM_INT); $query->bindParam(':upassword',$hashedpass,PDO::PARAM_STR); $query->execute(); $lastInsertId = $dbh->lastInsertId(); if($lastInsertId) { $msg="You have signup Scuccessfully"; } else { $error="Something went wrong.Please try again"; } } else { $error="Username or Email-id already exist. Please try again"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>PDO | Registration Form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script> <style> .errorWrap { padding: 10px; margin: 0 0 20px 0; background: #fff; border-left: 4px solid #dd3d36; -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,.1); box-shadow: 0 1px 1px 0 rgba(0,0,0,.1); } .succWrap{ padding: 10px; margin: 0 0 20px 0; background: #fff; border-left: 4px solid #5cb85c; -webkit-box-shadow: 0 1px 1px 0 rgba(0,0,0,.1); box-shadow: 0 1px 1px 0 rgba(0,0,0,.1); } </style> <!--Javascript for check username availability--> <script> function checkUsernameAvailability() { $("#loaderIcon").show(); jQuery.ajax({ url: "check_availability.php", data:'username='+$("#username").val(), type: "POST", success:function(data){ $("#username-availability-status").html(data); $("#loaderIcon").hide(); }, error:function (){ } }); } </script> <!--Javascript for check email availability--> <script> function checkEmailAvailability() { $("#loaderIcon").show(); jQuery.ajax({ url: "check_availability.php", data:'email='+$("#email").val(), type: "POST", success:function(data){ $("#email-availability-status").html(data); $("#loaderIcon").hide(); }, error:function (){ event.preventDefault(); } }); } </script> </head> <body> <form class="form-horizontal" action='' method="post"> <fieldset> <div id="legend" style="padding-left:4%"> <legend class="">Register | <a href="index.php">Sign in</a></legend> </div> <!--Error Message--> <?php if($error){ ?><div class="errorWrap"> <strong>Error </strong> : <?php echo htmlentities($error);?></div> <?php } ?> <!--Success Message--> <?php if($msg){ ?><div class="succWrap"> <strong>Well Done </strong> : <?php echo htmlentities($msg);?></div> <?php } ?> <div class="control-group"> <!-- Full name --> <label class="control-label" for="fullname">Full Name</label> <div class="controls"> <input type="text" id="fname" name="fname" pattern="[a-zA-Z\s]+" title="Full name must contain letters only" class="input-xlarge" required> <p class="help-block">Full can contain any letters only</p> </div> </div> <div class="control-group"> <!-- Username --> <label class="control-label" for="username">Username</label> <div class="controls"> <input type="text" id="username" name="username" onBlur="checkUsernameAvailability()" pattern="^[a-zA-Z][a-zA-Z0-9-_.]{5,12}$" title="User must be alphanumeric without spaces 6 to 12 chars" class="input-xlarge" required> <span id="username-availability-status" style="font-size:12px;"></span> <p class="help-block">Username can contain any letters or numbers, without spaces 6 to 12 chars </p> </div> </div> <div class="control-group"> <!-- E-mail --> <label class="control-label" for="email">E-mail</label> <div class="controls"> <input type="email" id="email" name="email" placeholder="" onBlur="checkEmailAvailability()" class="input-xlarge" required> <span id="email-availability-status" style="font-size:12px;"></span> <p class="help-block">Please provide your E-mail</p> </div> </div> <div class="control-group"> <!-- Mobile Number --> <label class="control-label" for="mobilenumber">Mobile Number </label> <div class="controls"> <input type="text" id="mobilenumber" name="mobilenumber" pattern="[0-9]{10}" maxlength="10" title="10 numeric digits only" class="input-xlarge" required> <p class="help-block">Mobile Number Contain only 10 digit numeric values</p> </div> </div> <div class="control-group"> <!-- Password--> <label class="control-label" for="password">Password</label> <div class="controls"> <input type="password" id="password" name="password" pattern="^\S{4,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Must have at least 4 characters' : ''); if(this.checkValidity()) form.password_two.pattern = this.value;" required class="input-xlarge"> <p class="help-block">Password should be at least 4 characters</p> </div> </div> <div class="control-group"> <!-- Confirm Password --> <label class="control-label" for="password_confirm">Password (Confirm)</label> <div class="controls"> <input type="password" id="password_confirm" name="password_confirm" pattern="^\S{4,}$" onchange="this.setCustomValidity(this.validity.patternMismatch ? 'Please enter the same Password as above' : '')"" class="input-xlarge"> <p class="help-block">Please confirm password</p> </div> </div> <div class="control-group"> <!-- Button --> <div class="controls"> <button class="btn btn-success" type="submit" name="signup">Signup </button> </div> </div> </fieldset> </form> <script type="text/javascript"> </script> </body> </html> |
index.php (login page)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
<?php session_start(); //Database Configuration File include('config.php'); error_reporting(0); if(isset($_POST['login'])) { // Getting username/ email and password $uname=$_POST['username']; $password=$_POST['password']; // Fetch data from database on the basis of username/email and password $sql ="SELECT UserName,UserEmail,LoginPassword FROM userdata WHERE (UserName=:usname || UserEmail=:usname)"; $query= $dbh -> prepare($sql); $query-> bindParam(':usname', $uname, PDO::PARAM_STR); $query-> execute(); $results=$query->fetchAll(PDO::FETCH_OBJ); if($query->rowCount() > 0) { foreach ($results as $row) { $hashpass=$row->LoginPassword; } //verifying Password if (password_verify($password, $hashpass)) { $_SESSION['userlogin']=$_POST['username']; echo "<script type='text/javascript'> document.location = 'welcome.php'; </script>"; } else { echo "<script>alert('Wrong Password');</script>"; } } //if username or email not found in database else{ echo "<script>alert('User not registered with us');</script>"; } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- This file has been downloaded from Bootsnipp.com. Enjoy! --> <title>PDO | Login form</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> </head> <body> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> <div id="login-overlay" class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Login Form</h4> </div> <div class="modal-body"> <div class="row"> <div class="col-xs-6"> <div class="well"> <form id="loginForm" method="post"> <div class="form-group"> <label for="username" class="control-label">Username / Email id</label> <input type="text" class="form-control" id="username" name="username" required="" title="Please enter you username or Email-id" placeholder="email or username" > <span class="help-block"></span> </div> <div class="form-group"> <label for="password" class="control-label">Password</label> <input type="password" class="form-control" id="password" name="password" placeholder="Password" value="" required="" title="Please enter your password"> <span class="help-block"></span> </div> <button type="submit" class="btn btn-success btn-block" name="login">Login</button> </form> </div> </div> <div class="col-xs-6"> <p class="lead">Register now for <span class="text-success">FREE</span></p> <ul class="list-unstyled" style="line-height: 2"> <li><span class="fa fa-check text-success"></span> Lorem ipsum dolor sit amet</li> <li><span class="fa fa-check text-success"></span>Lorem ipsum dolor sit amet</li> <li><span class="fa fa-check text-success"></span>Lorem ipsum dolor sit amet</li> <li><span class="fa fa-check text-success"></span>Lorem ipsum dolor sit amet</li> <li><span class="fa fa-check text-success"></span> Lorem ipsum dolor sit amet</li> </ul> <p><a href="signup.php" class="btn btn-info btn-block">Yes please, register now!</a></p> </div> </div> </div> </div> </div> <script type="text/javascript"> </script> </body> </html> |
How to run this script
1. Download and Unzip the file on your local system.
2. copy passwordhashing folder and put this file inside root directory(for xampp is htdocs,for wamp is www and for lamp is var/www/)
3. Database Configuration
Open phpmyadmin
http://localhost/phpmyadmin
Create Database pdosignup.
Import database pdosignup.sql(file available inside the pacakege)
Open Your browser put inside browser “http://localhost/passwordhashing /”