Click here to Skip to main content
14,666,484 members
Articles » Web Development » PHP » General
Tip/Trick
Posted 2 Feb 2016

Tagged as

Stats

30.1K views
6 bookmarked

Login/logout and Session Id Cookies in PHP for Beginners

Rate this:
4.00 (3 votes)
Please Sign up or sign in to vote.
4.00 (3 votes)
2 Feb 2016CPOL
Fastest and most primitive way to get started

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?

  1. User submits login form. Form sends login and password to PHP. 
  2. 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.
  3. User visits any page on this domain and browser sends a cookie to server for each request.
  4. 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.
  5. 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?

  1. Any local PHP server or hosting with PHP
  2. Notepad

Using the Code

index.php

<?php

session_start(); //gets session id from cookies, or prepa

if (session_id() == '' || !isset($_SESSION['login'])) { //if sid exists and login for sid exists
  
?>

<a href="/login.php">Login</a>

<?php

} else {

  echo "Hi, " . $_SESSION['login'];

?>

<a href="/logout.php">Logout</a>

<?php 

}

?>

login.php

<?php

session_start();

//TODO: do not hardcode, get from database
const login = 'admin';
const password = 'admin';

if (isset($_POST['login']) && isset($_POST['password'])) //when form submitted
{
  if ($_POST['login'] === login && $_POST['password'] === password)
  {
    $_SESSION['login'] = $_POST['login']; //write login to server storage
    header('Location: /'); //redirect to main
  }
  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); //send browser command remove sid from cookie
session_destroy(); //remove sid-login from server storage
session_write_close();
header('Location: /');

?>

History

  • 02/02/2016: Initial version posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Brahmaputra Mehta
Bangladesh Bangladesh
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --