The following code must be included (with require_once
) in all pages that are only accessible to authorized users:
<?php session_start(); if ( ! isset($_SESSION['authorized']) ) { $current_url = urlencode( $_SERVER['PHP_SELF'] ); header("Location: login.php?redirect=$current_url"); }
First, you can check for the session variable. If the user is not authenticated, redirect the user to the login page. As you might have seen, the current URL ($_SERVER['PHP_SELF']
) is provided as a GET parameter, so, if available, the login code redirects the user back to where the user came from.
The script login.php
, to which the preceding code redirects the user, contains an HTML form, after successful authentication, the user is redirected back to where she came from (or redirected to the dashboard).
Checking the User Credentials
<?php session_start(); /* If user is already authenticated, redirect user to the Dashboard. */ if ( isset($_SESSION['authorized']) ) { header('Location: dashboard.php'); exit; } // Show login page and validate the form if ($_SERVER['REQUEST_METHOD'] == 'POST') { validate_form($_POST); } else { print_form(); } // Validate user function validate_form($form) { $user = $form['user'] ?? ''; // php null coalescing operator $pass = $form['pass'] ?? ''; $redirect = $form['redirect'] ?? ''; $redirect = $redirect ?: 'dashbaord.php'; //Shorthand ternary operator //redirect authenticated user to secure area if ($user == 'Admin' && $pass == 'brainbell') { $_SESSION['authorized'] = 1; $_SESSION['user'] = $user; header("Location: $redirect"); exit; } // show error message if login failed print_form('<p>Login failed</p>'); } //login form function print_form($message = '') { echo $message; ?> <form method="post" action=""> Username: <input type="text" name="user" value=""> Username: <input type="password" name="pass" value=""> <input type="hidden" name="redirect" value="<?=$_GET['redirect'] ?? ''?>"> <input type="submit" name="submit" value="submit"> </form> <?php }
The login form notes the referring page in the URL. The approach is simple after the user is authenticated, write this information into a session variable. On all protected pages, check for the presence of this session variable.
Cookies and Sessions: