Online Shopping : Computers : Programming : Languages : PHP : Common Problems : Sessions and State

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

78 of 108 people (72%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I check a users login and password on every page visit?
How can I maintain data across pages for a visitor?
Does PHP have support for sessions?
How can I force a member to login?

Jan 21st, 2008 16:52
Tim Stumbaugh, Ben Munoz, Jeff Wilcox, Nathan Wallace, Zend Technologies (Tutorials Area)


HTTP is a stateless protocol.  Each request to the server is completely
independent of the other requests from the same browser.  It is possible
however to support user sessions through the use of persistent data on
the server side and cookies or form variables on the client side.
PHPLIB is a great set of classes wihch has already completed solved the
problem of session management and user authentication.  It is free for
use in your scripts.
    http://phplib.netuse.de
PHP 4 / ZEND USERS 
================== 
If you're using PHP 4 on your server, especially one of the more recent 
beta versions of RC1, then you're in luck!  By simply editing your 
php.ini file, you can setup file-based session management.  It's also 
possible to extend this to save sessions in any way.
If you go to 
http://www.zend.com/zend/tut/session.php 
You can read a good tutorial on using the built-in session capabilities 
in PHP4, and learn about how the system is setup.
PHPLIB may still be more suitable for you if you have written a complex 
site around it already, or if you're doing more advanced things with 
sessions.
A good quick example of the PHP4-sessions way of doing things is their 
counter example:
session_start(); 
print($counter); 
$counter++;
session_register("counter");
------------------------------------------------------
A quick login check example:
<?
session_start();
if ($_GET["enter"]==1){ //user clicked script.php?enter=1, check user/pw
here
    $_SESSION["logged_in"] = TRUE;
    print ("Logging In");
}
if ($_GET["exit"]==1) { //user wants to logout by clicking script.php?exit=1
    destroy_session();
    print ("Logging Out");
}
if ($_SESSION["logged_in"]) { //prints logged in status
    print ("Logged In");
} else {
    print ("Logged Out");
}
?>