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 phrase 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 (see also Figure 5.9) 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 (login.php; excerpt)
 <?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");   } ?> 

Figure 5.9. The login formnote the referring page in the URL.


And that's it! The script secret.php in the download archive contains some quite secret information and is protected by the code in Listings 5.21 and 5.22.




PHP Phrasebook
PHP Phrasebook
ISBN: 0672328178
EAN: 2147483647
Year: 2005
Pages: 193

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net