Log in with PHP

Sometimes you may want to protect part of your website from unwanted visitors, for example, the page which allows you to change the settings of your website. This is possible in PHP. First of all, you have to organize your website and decide which parts you want to protect and which parts you want to keep open. Once you've decided which pages you want to protect, use this tutorial!!

Start by making a login form on a public page, where you will be able to enter your login data. This code can be included anywhere on the page.

<form method='post' action='login.php'>
 <table><tr><td>Username:</td><td><input type='text' name='username'></td></tr>
 <tr><td>Password:</td><td><input type='password' name='password'></td></tr>
 <tr><td></td><td><input type='submit' name='submit' value='Log in'></td></tr></table>

At the beginning, you specify the transfer method, in this case POST. The action attribute specifies which page the user will be sent to when he clicks the submit button. Then there's a table in which there are two input boxes and a submit button, one box for the username and the other one for the password.

Now we want to make a page (login.php) which checks if the user has put in a valid username-password combination and logs in the user. First you have to set the variable which checks if the user can log in to false to avoid some security problems:
$logIn = false

Then you have to check the user has the right to log in. In this tutorial I will use mysql data for the login credentials, but you can use any function you want in PHP. Just skip this part and set the variable we just made to true when the user can log in. First you have to connect to the mysql database:
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = 'password';
//do the connection
$conn = mysql_connect($dbhost, $dbuser, $dbpassword) or die ('Error connecting to mysql');
//open a specific database
$dbname = 'myDatabase';
mysql_select_db($dbname, $conn);

Now we're connected, we want to test the user input. But don't forget the input has to be checked before putting it in the query, as some people find it funny to hack into your site.
//First check the user input
if(get_magic_quotes_gpc()) {
 $username = stripslashes($_POST['username']);
 $password = stripslashes($_POST['password']);
} else {
 $username = $_POST['username'];
 $password = $_POST['password'];
$username = mysql_escape_string($_POST['username'], $conn);
$password = mysql_escape_string($_POST['password'], $conn);
//Then make the query and execute it
$query = "SELECT * FROM LOGINTABLE WHERE Username = '".$username."' and Password = '".$password."'";
$query_result = mysql_query($query);
//If there is one result the user can be logged in
if (mysql_num_rows($query_result)==1){
 $logIn = true;
 $logIn = false;
//And close the mysql connection

Remark: NEVER put the passwords of your users as clear-text in the database. This tutorial is to help you unerstand the basics of a login script, and shouldn't directly be used in a security-sensitive (non-local) context. See for more information.

The user input has been checked and the $logIn boolean has been set to the correct value. The user can now be logged in or sent back to the homepage of your site:

//If the user can log in
 //Start the session and set the OK var to true
 $_SESSION["OK"] = true;
 //And send the user to the private part of your website
 header("Location: loggedIn.php");
 //If the user isn't logged in, send him back to the homepage
 header("Location: index.php");

The user has been logged in and sent to the page which is reserved for the users who have logged in. But someone could try to access the page directly by accessing the page directly from his web browser. To prevent this, we have to check if the user has been logged in at each page request by including a file which checks if the Session variable has been set (check.php):

//Start the session if it hasn't been started yet
//Check if the user has been logged in
if(!isset($_SESSION["OK"]) || $_SESSION["OK"] == false){
 //If he hasn't, send him back to the homepage
 echo "<meta http-equiv='refresh' content='3;URL=index.php'/>Please log in";
//Tell your program the session has been started. This will prevent some useless error messages
define("SESSIONSTARTED", 1);

Now we have a file we can include (actually require) at the beginning of each file where the user has to be logged in by using the following code:

//Insert the rest of your code here

Congratulations! You now have a way to protect some of your pages. But there is still one more problem, the user needs to be able to log out. This is quite useful if you want to log in in a webcafe and you don't want the next person to access the site with your login data. We need one more page (logout.php) which logs out the user.

//First check if the user is logged in, this again prevents some error messages
//Delete the session variables
//And send the user back to the homepage
echo "<meta http-equiv='refresh' content='3;URL=index.php'/>You have been logged out";

You now have a fully working login system. You can download all files here.

Search RSS
location of file
chris ( 17-02-2012 08:43:31

Hi! my only prob is where to put those file I will going to put it in one
or separate?
Sander (SAdministrator) 12-06-2012 00:16:53


You just need to include the check file in the "protected" pages.
[Moved from "Compare dates"]
Sander (SAdministrator) 11-05-2011 12:44:22

i created login and logout pages in php for html project.
After i logged
from the page, if i click back button it is showing the previous

logged out ,it should not go to previous page.
What i have to do
for this?
Sander (SAdministrator) 11-05-2011 17:05:37

Have you added the "require("check.php" )" part in each file?
check.php file :)
Jonas ( 21-04-2011 00:47:26

Hi there from Brazil!!!

Whats up?
I Really loved your article. at the moment, I
am just reading, then apply it latter.
So, what should I have inside of
check.php file? Thanks.

Take care, and keep doing the good work.
Sander (SAdministrator) 21-04-2011 08:49:37


It should contain all code snippets except for the first and the two
last. You can also download the zip file that contains all files with the link
at the end of the article.
a very nicely put particle.
Ibrahim Shiyam ( 15-10-2010 23:51:59

your article is very explanatory very much useful.

I hope to put this article
in my blog soon.
It didn't work
Sami ( 31-05-2010 20:23:23

The script didn't seem to work very well.
Sander (SAdministrator) 01-06-2010 07:55:16

Could you please be a bit more specific? What is the problem? Where doesn't it
work? What is the error message?
Sami (Registered) 06-06-2010 11:40:46

There is no error messange, it returns me back to the login page, even if I
enter the right username and password!
Sander (SAdministrator) 06-06-2010 13:28:51

I've put this in the forum. Please check here for the
emu boots
emu boots ( 21-02-2010 02:51:58

Your writing is very elegant, very vivid and lively, I really like you, wish you
continued to write better articles, I will often try to concern, oh!
Only registered users can write comments!

3.23 Copyright (C) 2007 Alain Georgette / Copyright (C) 2006 Frantisek Hliva. All rights reserved."