p2p.wrox.com Forums

Need to download code?

View our list of code downloads.


  Return to Index  

beginning_php thread: TIP: Simplified session-based page protection


Message #1 by "Nikolai Devereaux" <yomama@u...> on Mon, 3 Feb 2003 13:46:12 -0800
Another short tip, in light of recent session-related posts.

You should define functions which abstract the details of sessions and login
authentication from the main part of your scripts.

Define a function, logged_in(), which returns true if the user is logged in,
and false if not.

Define a login() function which accepts a username and password and returns
true if they were valid, and false if not.


The reason for this is that it's MUCH easier and cleaner to call
if(!logged_in()) at the top of each of your pages than it is to check the
existence of your session variable.


<?php // session.inc.php
session_start();

function logged_in()
{
   return isset($_SESSION['logged_in']) && $_SESSION['logged_in'];
}


function login($un, $pw)
{
   $query = "SELECT COUNT(*) FROM users
             WHERE username='$un'
               AND password='$pw'";

   $result = mysql_query($query);

   if($result && (mysql_result($result, 0) == 1))
   {
      $_SESSION['logged_in'] = true;
   }

   return logged_in();
}

?>



<?php // protected page:

require_once('session.inc.php');

if(!logged_in())
{
   // send to login page
}

// rest of content.


?>


Additionally, you can write a more useful function to do more or less the same
thing with one function call:


<?php // session.inc.php

function logged_in() {...}
function login() {...}


function protect_page()
{
   if(! logged_in())
   {
       // send to login page
   }
}

?>


<?php  // protected page.php

require_once('session.inc.php');

protect_page();

// rest of content...


?>



Hope this helps clean things up a bit!

Nik


  Return to Index