PHP

Creating a Secured Area with Sessions

session_start();
if (!(isset($_SESSION['authorized']) &&
  $_SESSION['authorized'] != '')) {
  header("Location: login.php?url={$_SERVER['PHP_SELF']}");
}

Sessions can be a great way to secure certain parts of a website. 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.

First, you can check for the session variable. The code from the beginning of This must be included (with require_once) in all pages that are only accessible for authorized users.

The script login.php, to which the preceding code redirects the user, contains an HTML form and checks whether the provided data is correct (you might have to add your own users and passwords). As you might have seen, the previous URL is provided as a GET parameter, so, if available, the login code redirects the user back to where she came from:

Checking the User Credentials
<?php
  if (isset($_POST['user']) && $_POST['user'] ==
   'Damon' &&
      isset($_POST['pass']) && $_POST['pass'] ==
        'secret') {
    session_start();
    $_SESSION['authorized'] = 'ok';
    $url = (isset($_GET['url'])) ? $_GET['url'] :
      'index.php';
    header("Location: $url");
  }
?>

The login form note the referring page in the URL.

And that's it!

by BrainBellupdated
Advertisement: