0% found this document useful (0 votes)
19 views4 pages

PHP Sessions Tutorial

Uploaded by

sure boy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views4 pages

PHP Sessions Tutorial

Uploaded by

sure boy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

PHP Session Handling 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.

2. How to use Sessions:

------------------------

- Start a session with session_start() function at the top of your PHP file.

- Store data using the $_SESSION superglobal.

- Retrieve data using the $_SESSION superglobal in any PHP file.

- Destroy session data with session_unset() and session_destroy().

3. Implementing Session in Login System:

- login.php:

- Start session and store the username when the user successfully logs in.

- Redirect to dashboard.php if login is successful.

- 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:

- Destroy the session to log the user out.

- Redirect to the login page after logout.

Code Examples:

1. login.php

-------------

<?php

session_start(); // Start session

include 'config.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$username = $_POST['username'];

$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";

$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {

// Store username in session

$_SESSION['username'] = $username;

// Redirect to dashboard.php
header("Location: dashboard.php");

exit();

} else {

echo "Invalid credentials.";

mysqli_close($conn);

?>

2. dashboard.php

-----------------

<?php

session_start(); // Start session

// Check if the session is set

if (!isset($_SESSION['username'])) {

// Redirect to login if session not found

header("Location: login.html");

exit();

echo "<h2>Welcome, " . $_SESSION['username'] . "!</h2>";

echo "<p>You are now logged in.</p>";

echo "<a href='logout.php'>Logout</a>";

?>
3. logout.php

-------------

<?php

session_start(); // Start session

// Unset session data

session_unset();

// Destroy session

session_destroy();

// Redirect to login page

header("Location: login.html");

exit();

?>

You might also like