PHP & MySQL Login System Tutorial
Ranked #1,246 in Internet, #70,771 overall
Creating a login system
The database
Creating the MySQL Database.
SQL Code
CREATE TABLE IF NOT EXISTS `users` (
`id` int(250) NOT NULL AUTO_INCREMENT,
`username` varchar(25) NOT NULL,
`password` varchar(250) NOT NULL,
`email` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
INSERT INTO `users` (`id`, `username`, `password`, `email`) VALUES
(1, 'admin', '21232f297a57a5a743894a0e4a801fc3', 'admin@admin.com');
The script
Creating the actual script.
login.php
<form method="POST" action="login.php">
<b>Username:</b> <br /> <input type="text" name="username"> <p>
<b>Password:</b> <br /> <input type="password" name="password"> <p>
<input type="submit" name="submitLogin" value="Login!">
</form>
Now that we have created the form, we need to handle the user's data input upon submission of the form. We can check whether the form was submitted by checking whether the POST array was created, or more precisely: whether $_POST['submitLogin'] is set. If so: then the form was submitted through the POST method and we'll want to verify the login. Otherwise: the form hasn't been submitted yet and we'll want to display the form.
<?php
if(isset($_POST['submitLogin'])) { //form submitted?
//verify login from user input
}else{
//show login form
?>
<form method="POST" action="login.php">
<b>Username:</b> <br /> <input type="text" name="username"> <p>
<b>Password:</b> <br /> <input type="password" name="password"> <p>
<input type="submit" name="submitLogin" value="Login!">
</form>
<?php
}
?>
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
Now we need to create a mysql_query that attempts to select the user from the database ( with username = $username and password = $password , as given/input by the user ). Then we need to count the amount of rows found by this query ( if any ) and this way we can verify whether there is a user with the given username and password and thus whether it's a valid login. We do this within the mysql query using the COUNT statement and we call the amount of results found 'amount'.
$select_user = mysql_query("SELECT COUNT(id) AS amount FROM users WHERE username = '$username' AND password = '$password' ");
$user = mysql_fetch_assoc($select_user);
$amount_found = (int)$user['amount']; //amount of users found by the query
All we need to do next is check whether $amount_found is greater than 0. Or in other words: whether any users were found that matched the given username and password as provided by the user. If so: then it's a valid login, otherwise it's an invalid login ( no user matched the login username and password combination provided ). For a valid login we create a session variable $_SESSION['loggedin'] indicating that the user is logged in, and a session variable $_SESSION['username'] holding the username of the user logged in.
if($amount_found > 0) {
echo "Successfully logged in!";
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $username;
}else{
echo "Invalid login! Click <a href='login.php'>here</a> to try again.";
}
<?php
session_start(); //we're using sessions so this is required!
if(isset($_POST['submitLogin'])) { //form submitted?
//verify login from user input
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$select_user = mysql_query("SELECT COUNT(id) AS amount FROM users WHERE username = '$username' AND password = '$password' ");
$user = mysql_fetch_assoc($select_user);
$amount_found = (int)$user['amount']; //amount of users found by the query
if($amount_found > 0) {
echo "Successfully logged in! Click <a href='login.php'>here</a> to continue.";
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $username;
}else{
echo "Invalid login! Click <a href='login.php'>here</a> to try again.";
}
}else{
//show login form
?>
<form method="POST" action="login.php">
<b>Username:</b> <br /> <input type="text" name="username"> <p>
<b>Password:</b> <br /> <input type="password" name="password"> <p>
<input type="submit" name="submitLogin" value="Login!">
</form>
<?php
}
?>
Now there's one more thing we'll want to add: an if loop that checks if the user is already logged in ( by checking whether $_SESSION['loggedin'] is set to TRUE ). Because in that case we'll want to display a members page or something:
<?php
session_start(); //we're using sessions so this is required!
if($_SESSION['loggedin'] == TRUE) {
echo "Welcome back, ".htmlspecialchars($_SESSION['username'])."!";
}else{
if(isset($_POST['submitLogin'])) { //form submitted?
//verify login from user input
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$select_user = mysql_query("SELECT COUNT(id) AS amount FROM users WHERE username = '$username' AND password = '$password' ");
$user = mysql_fetch_assoc($select_user);
$amount_found = (int)$user['amount']; //amount of users found by the query
if($amount_found > 0) {
echo "Successfully logged in! Click <a href='login.php'>here</a> to continue.";
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $username;
}else{
echo "Invalid login! Click <a href='login.php'>here</a> to try again.";
}
}else{
//show login form
?>
<form method="POST" action="login.php">
<b>Username:</b> <br /> <input type="text" name="username"> <p>
<b>Password:</b> <br /> <input type="password" name="password"> <p>
<input type="submit" name="submitLogin" value="Login!">
</form>
<?php
}
}
?>
Usage
How to use our script.
mysql_connect("localhost", "root", "password");
mysql_select_db("webcodez");
If you'd like to include the login system into another page, you'll want to delete the session_start(); line at the top of the login.php page and put that at the top of your actual webpage. E.g.:
your_webpage.php
<?php
session_start();
include_once("login.php");
?>
To create a members area page for our login system, we can simply use the sessions $_SESSION['loggedin'] to verify whether a user is logged in, and the session $_SESSION['username'] to get the username of the logged in person. Do make sure, again, that we call session_start() at the top of the page first:
members.php
<?php
session_start();
if($_SESSION['loggedin'] == TRUE) { //loggedin already
echo "Welcome back, ".htmlspecialchars($_SESSION['username']);
}else{ //not logged in yet
include_once('login.php'); //show login page
}
?>
<?php
session_start(); //we're using sessions so this is required!
if($_SESSION['loggedin'] == TRUE) {
header('location: members.php'); //members area
}else{
if($_POST['submitLogin']) {
//verify login from user input
$username = mysql_real_escape_string($_POST['username']);
$password = md5(mysql_real_escape_string($_POST['password']));
$select_user = mysql_query("SELECT COUNT(id) AS amount FROM users WHERE username = '$username' AND password = '$password' ");
$user = mysql_fetch_assoc($select_user);
$amount_found = (int)$user['amount']; //amount of users found by the query
if($amount_found > 0) {
$login_attempt = 1; //successful login attempt
$_SESSION['loggedin'] = TRUE;
$_SESSION['username'] = $username;
header('location: members.php'); //members area
}else{
$login_attempt = 0; //invalid login attempt
}
}
if( ($_POST['submitLogin'] AND isset($login_attempt) AND $login_attempt = 0) OR !$_POST['submitLogin'] ) {
//show login form
if($_POST['submitLogin']) { //attempted to login? (-> invalid login)
echo "<p>Invalid login. </p>";
}
?>
<form method="POST" action="login.php">
<b>Username:</b> <br /> <input type="text" name="username"> <p>
<b>Password:</b> <br /> <input type="password" name="password"> <p>
<input type="submit" name="submitLogin" value="Login!">
</form>
<?php
}
}
?>
Logout
To logout the user simply unset the sessions that indicate a logged in user ($_SESSION['loggedin'] and $_SESSION['username']):
unset($_SESSION['loggedin']);
unset($_SESSION['username']);
if($_GET['do'] == "logout") {
unset($_SESSION['loggedin']);
unset($_SESSION['username']);
}
You might also like ...
Comments & Questions
Got any questions about the tutorial or just want to comment? This is the place to do so.
-
-
dogface
Aug 19, 2011 @ 1:02 pm | delete
- I didn't read every word, but I saw you used md5. You know it's not very safe, don't you? Bcrypt is the way to go: http://stackoverflow.com/questions/4795385/how-do-you-use-bcrypt-for-hashing-passwords-in-php
-
Related Products (Amazon)
Related Products (eBay)
by webcodez
"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."
webcodez
GameHeroes
more »
- 21 featured lenses
- Winner of 14 trophies!
- Top lens » PHP & MySQL Poll System Tutorial
Explore related pages
- PHP & MySQL Poll System Tutorial PHP & MySQL Poll System Tutorial
- PHP & MySQL Visitors Counter Tutorial PHP & MySQL Visitors Counter Tutorial
- PHP basics tutorial PHP basics tutorial
- PHP Banner Rotator Tutorial PHP Banner Rotator Tutorial
- PHP Smilies System Tutorial PHP Smilies System Tutorial
- PHP Email Validation Tutorial PHP Email Validation Tutorial