06 Jan 2015
PHP Login Script using PDO
Are you looking for basic PHP login script. In this tutorial I want to discuss how to create a login page using PHP/MySQL with PDO Query , welcome and logout page. If you are a PHP beginner take a quick look at this live demo with Username : demo Password :demo.
This tutorial will explain you creating user tables, posting form values,storing and destroying the session values, PDO database connection and fetch records from DB using PDO.
Create basic user table structure:
1 2 3 4 5 6 7 8 9 |
CREATE TABLE `tbl_users` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(100) NULL DEFAULT NULL, `password` VARCHAR(72) NULL DEFAULT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB |
Database Connection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//DB configuration Constants define('_HOST_NAME_', 'localhost'); define('_USER_NAME_', 'XXXXXXX'); define('_DB_PASSWORD', 'XXXXXXX'); define('_DATABASE_NAME_', 'XXXXXXXX'); //PDO Database Connection try { $databaseConnection = new PDO('mysql:host='._HOST_NAME_.';dbname='._DATABASE_NAME_, _USER_NAME_, _DB_PASSWORD); $databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage(); } |
index.php (Contains PHP and HTML Code)
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 |
<?php session_start(); //DB configuration Constants define('_HOST_NAME_', 'localhost'); define('_USER_NAME_', 'XXXXXX'); define('_DB_PASSWORD', 'XXXXXX'); define('_DATABASE_NAME_', 'XXXXXXX'); //PDO Database Connection try { $databaseConnection = new PDO('mysql:host='._HOST_NAME_.';dbname='._DATABASE_NAME_, _USER_NAME_, _DB_PASSWORD); $databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo 'ERROR: ' . $e->getMessage(); } if(isset($_POST['submit'])){ $errMsg = ''; //username and password sent from Form $username = trim($_POST['username']); $password = trim($_POST['password']); if($username == '') $errMsg .= 'You must enter your Username<br>'; if($password == '') $errMsg .= 'You must enter your Password<br>'; if($errMsg == ''){ $records = $databaseConnection->prepare('SELECT id,username,password FROM tbl_users WHERE username = :username'); $records->bindParam(':username', $username); $records->execute(); $results = $records->fetch(PDO::FETCH_ASSOC); if(count($results) > 0 && password_verify($password, $results['password'])){ $_SESSION['username'] = $results['username']; header('location:dashboard.php'); exit; }else{ $errMsg .= 'Username and Password are not found<br>'; } } } ?> <html> <head><title>Login Page PHP Script</title></head> <body> <div align="center"> <div style="width:300px; border: solid 1px #006D9C; " align="left"> <?php if(isset($errMsg)){ echo '<div style="color:#FF0000;text-align:center;font-size:12px;">'.$errMsg.'</div>'; } ?> <div style="background-color:#006D9C; color:#FFFFFF; padding:3px;"><b>Login</b></div> <div style="margin:30px"> <form action="" method="post"> <label>Username :</label><input type="text" name="username" class="box"/><br /><br /> <label>Password :</label><input type="password" name="password" class="box" /><br/><br /> <input type="submit" name='submit' value="Submit" class='submit'/><br /> </form> </div> </div> </div> </body> </html> |
NOTE: password_verify() required PHP version >=5.5. So use another hashing if your server don’t have PHP version 5.5 or greter.
Dashboard (welcome page after login)
1 2 3 4 5 |
<?php session_start(); echo 'Welcome '.$_SESSION['username']; ?> |
Logout
1 2 3 4 5 6 7 |
<?php session_start(); session_destroy(); header("location:index.php"); exit; ?> |
Great tutorial Saurabh Kumar Singh. I’m having little problem though, I’m kind of a newbie in this PDO thing so I don’t know how to fix it. I’ve got two errors one I’ve solved, the other one I just can’t seem to understand, I got this error line : Fatal error: Call to undefined function password_verify() in C:\xampp\htdocs\login\index.php on line 36
You need PHP 5.5. Upload a phpinfo file to your server to find out which version you have. Google how to do it.
Line 32 of index.php appears to contain a spelling error: variable $errMsg is misspelled.
Line 32: if($errMSG == ”){
Should be: if($errMsg == ”){
Thanks for sharing this script.
Thanks Jim..
What I am challenged with Saurabh is how to verify the hashed password in the MySQL table against the “non-hashed” password being entered into the Login Form.
I see in your code — password_verify($password, $results['password'] — which is close to what PHP.net shows: password_verify ( string $password , string $hash ). It appears that your code matches what the user enters against the database, but since it is not hashed it cannot match.
Perhaps this is why I cannot get your code to function. If you can enlighten me, I would appreciate it.
Thanks,
Jim
Florida, USA
Hi Jim,
The password which are saved in database must be hashed by password_hash(). If you provide me the code and database password string then I can take a look and help you.
Hi Saurabh ,
Thanks for offering to help. I now grasp how password_hash() and password_verify() functions work: password_verify() requires the hashed password from the database table. Once I figured out the PHP PDO code to get it, I was able to get the code functional. Thank you for sharing your knowledge. PHP PDO information is not readily available online. I want to use only PDO. Perhaps you should consider adding a donation button to allow donations.
Florida, USA
Error to send to dashboard, Why?
Notice: Undefined index: username in C:\wamp\www\dashboard.php on line 4
Thank you very much
provide us the full script at sksingh[at]stepblogging[dot]com. We will check and get back to you with the solution.
Hi there, great job with tutorial but I must say that I hit a bit of a wall here using your code.
First I noticed when I bind parameters like this:
$records->bindParam(‘:username’, $username);
I get this message –> Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY093]: Invalid parameter number: parameter was not defined’
So, to fix error above I changed parameter like this–> $records->bindParam(‘:password’, $username);
But this “fix” raised another issue: Now, I can’t log in and access dashboard.php. I get error message Username and Password are not found.
What is possible solutions to this problem?
Thank you!
Hi Svinjica,
Provide us the full code for any assistance, after analysis the code we will let you know the issues. send us the code on sksingh[at]stepblogging[dot]com
no works can help me ?
provide us your script, we will verify and let us know the issue.
Hi, i was just wondering whether passwordHash() is used to store the password in the database so that you can compare with the login using password_verify(). I have the passwords stored in mySql and have the type binary 60 and the website I’m doing does not have a register form where the user can insert into database. How am i able to compare? I’m sorry for the stupid question, I am a beginner and im trying to learn to do my project >< help is much appreciated.
change the password fields in database to varchar.
During save using password_hash() and when you required to check use password_verify(). If you still facing any problem. Drop me your source code, i will surely help you.
It is a nice script. In your script $errMsg is a string. I think it should be an array, so if we did not enter username and password both error message will be displayed. I do not know if I am correct. Otherwise it is really good. Keep up the nice work…
your demo is accepting any username and pass.
yes.. please try username: demo and Password: demo
sir
after logout when we click back it goes to dashboard.php? Kindly help us to solve this issue?
you can check the session at the top of page. if(!$_SESSION['username']){ header(“location:index,php”); exit;}
Excellent.. thanks for this example.
I am student and I need create a project with xampp, php 7, pdo and using class to connect with mysql. You will have a any project with that characteristics.
and I searched the web, but can not find a project that gives me the idea of how to develop it.
thank you very much, I hope you can help me.
Yes surely I will help you. Please send me your requirement at sksingh@stepblogging.com in detail.