PHP Login System

Following up on yesterday’s introduction to PHP Sessions, let’s talk about building a simple login system in PHP. To start, you will need to make sure that pages on your site that are behind the login page will have sessions enabled. This can be done for all of your pages by setting the php.ini variable session.auto_start or making sure to include session_start() at the top of your pages. For this walkthrough we’ll be creating a small site that had 4 pages: main index (the home page), login and logout pages and a restricted access page. For the sake of simplicity we’ll be using a hardcoded username and plaintext password. For obvious reasons we don’t recommend doing so and at the very least you should be encrypting the password.

To start off, let’s put together our home page index.php:

<?php
// Starts the session
session_start

// Checks if the user is logged in
if (isset($_SESSION['username']) && $_SESSION['username'] == 'admin'))
{
	echo 'Hello administrator, would you care to access the <a href="/secret.php">secret page</a> or <a href="/logout.php">logout</a>?'
}
else
{
	echo 'Hello stranger, if you the admin you could <a href="/login.php">login</a>.'
}
?>

Nothing fancy, we start the session and check to see if the username is set in the session. If it is, give some secret options, if not, present the user with the opportunity to login. Speaking of logging in, on to the login page, login.php:

<?php
// Starts the session
session_start

// Checks if the user is logged in
if (isset($_SESSION['username']) && $_SESSION['username'] == 'admin'))
{
	// User is already logged in, send them home!
	header('Location: /'
	exit
}
else
{
	// Checks if the user is trying to log in
	if (isset($_POST['username'], $_POST['password']))
	{
		if (trim($_POST['username']) == 'admin' && trim($_POST['password']) == 'abc123')
		{
			$_SESSION['username'] = 'admin'

			// Successful login, send them home!
			header('Location: /'
			exit
		}
		else
		{
			echo 'Invalid login credentials, try again.'
		}
	}

	// Displays the login form
	?>
	<form method="post" action="/login.php">
		<label for="username">Username:</label><br>
		<input type="text" id="username" name="username"><br>
		<label for="password">Password:</label><br>
		<input type="text" id="password" name="password"><br>
		<input type="submit">
	</form>
	&lt;?php
}
?>

A bit more going on in this one, out of the gate we start our session and then check to see if the user is already logged in. If they are logged in, we send them back to the home page as there’s no reason for them to be logging in again. After that, we check to see if the login credentials have been supplied and check if they are valid. If they are not, we display an error, if correct send them back to the home page as they are now properly authenticated. Lastly we display the login form which is set up to post back to itself, that’s why all of the login logic exists in the same file. You could very well abstract out the login logic to it’s own file, perhaps login/process.php or something similar. As mentioned before, the username and password are hardcoded and it is not recommended for use outside of this example. The check if the information is correct could be swapped out to check a database or other datastore as well as hashing the password as you should never store plaintext passwords.

Now that you have out page to log the user in, let’s set up our “secret” page named secret.php. The page is very similar to our main index with the difference that unauthenticated users will be will served an HTTP Error Code (401 Unauthorized) instead of a message to log in.

<?php
// Starts the session
session_start

// Checks if the user is logged in
if (isset($_SESSION['username']) && $_SESSION['username'] == 'admin'))
{
	echo 'Welcome to the super secret page!'
}
else
{
	header("HTTP/1.0 401 Unauthorized"
}
?>

Now we have a page that’s completely locked out to unauthorized users. Last but not least, we need to write a log out script that will destroy the session. This file will be named logout.php and will be our shortest script because it doesn’t have any markup. To keep things simple we won’t check if the user is logged in or not, just destroy the session and redirect:

<?php
// Starts the session
session_start

// Destroys the session
session_destroy

// Kicks the user home
header('Location: /'
?>

That’s it, you now have a simple site that has a login system! Tomorrow’s post will be a continuation of PHP Sessions by delving into some advanced configuration options.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.