In this article I am going to create registration and login form using password_hash() function. Password_hash API was introduced in PHP 5.5. Right now password_hash only support BCrypt algorithm but PHP will update API in future to support more algorithms.
Syntax:
string password_hash ( string $password , integer $algo [, array $options ] )
Parameters:
string $password : user defined password.
integer $algo : Password Algorithm Constant. Currently PASSWORD_DEFAULT and PASSWORD_BCRYPT
PASSWORD_DEFAULT: Use the BCrypt algorithm to create the hash, but will be changed in future to create new and strong algorithms.
PASSWORD_BCRYPT: Use the CRYPT_BLOWFISH. This will always returns 60 characters string or false on failure.
array $options: An associative array having options. $options currently have 2 indexes. One is cost and second is salt. Cost is the iteration of algorithm which means how many times algorithm runs to make a strong hash. You must use cost value according to your server configuration. I, personally recommend using your cost value from 8 to 10. Salt Value is a user defined string use in creating a hash. If you provide your own salt then it prevents a salt from being atomically generated. In PHP 7.0.0 salt option is deprecated. It is better to use salt that is generated by default.
Note: If no option is given, random salt will be generated and default cost will be used.
In current post I am using simple registration and login form with no Javascript and PHP validation. I have created two different files one is for registration and second is for login. Database connection is stored on a different file name as config.php. Now let’s start.
Database Table:
1 2 3 4 5 6 7 8 9 10 11 12 |
CREATE TABLE `users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `first_name` VARCHAR(255) NULL DEFAULT NULL, `last_name` VARCHAR(255) NULL DEFAULT NULL, `email` VARCHAR(255) NULL DEFAULT NULL, `password` VARCHAR(255) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB AUTO_INCREMENT=2 ; |
I have created a users table with 5 fields (id, first_name, last_name, email, password) . PHP recommend to set 255 character lengths for password field because PASSWORD_BCRYPT returns 60 characters and PASSWORD_DEFAULT is constantly updating.
Database Connection: (config.php)
1 2 3 4 5 6 7 |
<?php $conn = mysqli_connect("localhost","root","","demo"); if(!$conn){ die("Connection error: " . mysqli_connect_error()); } ?> |
Registration Form: (registration.php)
Simple registration form with First Name, Surname, Email and Password fields. Form will be posted to the same page(registration.php).
1 2 3 4 5 6 7 8 |
<h1>Registration Form</h1> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <input type="text" name="first_name" value="" placeholder="First Name"> <input type="text" name="surname" value="" placeholder="Surname"> <input type="text" name="email" value="" placeholder="Email"> <input type="password" name="password" value="" placeholder="Password"> <button type="submit" name="submit">Submit</buttom> </form> |
Registration Form Submit: (registration.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php require_once("config.php"); if(isset($_POST['submit'])){ $firstName = $_POST['first_name']; $surName = $_POST['surname']; $email = $_POST['email']; $password = $_POST['password']; $options = array("cost"=>4); $hashPassword = password_hash($password,PASSWORD_BCRYPT,$options); $sql = "insert into users (first_name, last_name,email, password) value('".$firstName."', '".$surName."', '".$email."','".$hashPassword."')"; $result = mysqli_query($conn, $sql); if($result) { echo "Registration successfully"; } } ?> |
After submitting registration form we get all form values and store them in variables as you can see in the above code. $options is an array with cost index having a value of 4 (4 is the minimum value of cost, you can set any integer value according to your hardware configuration). $hashPassword variable is calling password_hash function with $password as a first parameter, PASSWORD_BCRYPT algorithm as a second parameter and $options as third parameter. $sql is an insert sql statement. $result is adding record in users table and if record insert successfully “Registration Successfully” print.
Login Form: (login.php)
Login form with email and password fields.
1 2 3 4 5 6 7 |
<h1>Login</h1> <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> <input type="text" name="email" value="" placeholder="Email"> <input type="password" name="password" value="" placeholder="Password"> <button type="submit" name="submit">Submit</button> </form> |
Login Form Submit: (login.php)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php require_once("config.php"); if(isset($_POST['submit'])){ $email = trim($_POST['email']); $password = trim($_POST['password']); $sql = "select * from users where email = '".$email."'"; $rs = mysqli_query($conn,$sql); $numRows = mysqli_num_rows($rs); if($numRows == 1){ $row = mysqli_fetch_assoc($rs); if(password_verify($password,$row['password'])){ echo "Password verified"; } else{ echo "Wrong Password"; } } else{ echo "No User found"; } } |
After submitting login form, get the value of email and password and trim them using trim function. $sql is a sql statement to check email address in users table. Get the num rows of sql statement and store it in $numRows variable. $numRows returns 1 then fetch associative array in $row variable against $sql statement. Then match $password with $row[‘password’] using password_verify() function. If both value match print “Password verified” else print “Wrong Password”;
Also read:
very nice…….
Perfect, thank you! We just implemented this into our login / register plugin to keep our users passwords safe, big update coming soon! login or register plugin easy to implement by one click 😉 OnceBuilder CMS
https://uploads.disquscdn.com/images/c65970930d84d09a2c829bfb841a305b0628f623ad5645c6c2aa62809749362f.png t
can i know why my page become blank after click the button login submit? please help me.
this is my code.
https://uploads.disquscdn.com/images/9f34069061d55195ac4008971204f7cf2aa0c045ad13bd0dfa13d3901942c4db.jpg
Hi Catherine,
Please check your connection.php file. Make sure there is no error on connection.php file. If possible paste here the code so i will also check.
Also in $sql in line 13. Your query should be select * from changePassword where email = ‘”$email.”‘.
You only need to check email address first if email address exist then $numRows = 1 and your condition will true.
this is my connection.php . and i already tried to fix line 13 like that but it doesnt work. it still become blank page.
Please! Attach your code with sql file. I will check and send you updated code.
https://uploads.disquscdn.com/images/1d39809429d71f9169685416648e38962d88fb54969001c7ab0784f1c2e90d87.jpg
this is my sql file.
Catherine you are facing error, because in connection.php you used mysqli class to create connection ie. new mysqli() and in submit code you are running query with mysqli functional mysqli_query(). On line no 15, 17 and 21 you must use $conn object.
so, what should i do?
use below code in your connection.php. and database, user, password accordingly
thank you! finally it works!
now my register also turn into blank page T.T but the data still save in the database.
https://uploads.disquscdn.com/images/b7f099c5d4ee8f737b5be0a8193834b7cd6aa76de90da49a4c0fa6330a06a5cf.jpg
Shouldn’t line 7 and 8 on login/registration for the submit button be
Submit
Yes thank you 🙂
Registration now has instead of