Introduction
In this tip, I will explain how to make the simplest authorization system with session id cookies on PHP.
Background
How Does Authorization Work?
- User submits login form. Form sends login and password to PHP.
- PHP validates login data, generates random string (session id), saves it to closed server storage in pair with user login, and sends session id to browser in response as cookie. Browser stores cookie.
- User visits any page on this domain and browser sends a cookie to server for each request.
- PHP checks if cookie has been sent, if such cookie exists in server storage with pair with login. Identifies user, provides access to his private content.
- Logout button removes the cookie from browser and sid-login pair from server storage. Browser does not send cookies, server does not see it and does not see sid-login pair.
What You Need?
- Any local PHP server or hosting with PHP
- Notepad
Using the Code
index.php
<?php
session_start();
if (session_id() == '' || !isset($_SESSION['login'])) {
?>
<a href="/login.php">Login</a>
<?php
} else {
echo "Hi, " . $_SESSION['login'];
?>
<a href="/logout.php">Logout</a>
<?php
}
?>
login.php
<?php
session_start();
const login = 'admin';
const password = 'admin';
if (isset($_POST['login']) && isset($_POST['password']))
{
if ($_POST['login'] === login && $_POST['password'] === password)
{
$_SESSION['login'] = $_POST['login'];
header('Location: /');
}
else
{
echo "<script>alert('Wrong login or password');</script>";
echo "<noscript>Wrong login or password</noscript>";
}
}
?>
<form method="post">
Login:<br><input name="login"><br>
Password:<br><input name="password"><br>
<input type="submit">
</form>
logout.php
<?php
session_start();
setcookie(session_name(), "", time() - 3600);
session_destroy();
session_write_close();
header('Location: /');
?>
History
- 02/02/2016: Initial version posted