PHP Sessions Tutorial
PHP Sessions Tutorial
In this tutorial, we learn how to use PHP sessions to manage user login and logout processes.
1. What is a Session?
--------------------------
A session is a way to store information (in variables) that can be accessed across multiple pages on
a website. It helps in tracking user data while they navigate between pages.
------------------------
- Start a session with session_start() function at the top of your PHP file.
- login.php:
- Start session and store the username when the user successfully logs in.
- dashboard.php:
- Check if the session variable is set. If not, redirect the user to the login page.
- Display the logged-in user's username.
- logout.php:
Code Examples:
1. login.php
-------------
<?php
include 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
if (mysqli_num_rows($result) > 0) {
$_SESSION['username'] = $username;
// Redirect to dashboard.php
header("Location: dashboard.php");
exit();
} else {
mysqli_close($conn);
?>
2. dashboard.php
-----------------
<?php
if (!isset($_SESSION['username'])) {
header("Location: login.html");
exit();
?>
3. logout.php
-------------
<?php
session_unset();
// Destroy session
session_destroy();
header("Location: login.html");
exit();
?>