PHP: Sessions

HTTP is a stateless protocol. So, how can we retain state (persistence)?  We will use sessions.

HTTP/PHP session information transfer model:

 

 

  • HTTP GET: parameters passed as part of URL:
    	http://phoenix.goucher.edu/process.php?name=tom
    
    Accessed through _GET associative array in PHP: 
    	$name = $_GET["name"];
    
    example:  Session ID (SID) passed as GET parameter: 
    	echo "<A href=\"http://phoenix.goucher.edu/process.php?"
         		. SID . "\">";

     

  • HTTP POST: parameters passed into script via stdin.
        Accessed through _POST associative array.

     

  • Session variables are maintained on the server and accessed by referring to a session ID and using the _SESSION associative array.
  • Sessions

    Sessions exist until browser is closed or PHP garbage collector removes the session data file.

    Establishing a session and writing session variables:

    	session_start();
    
    	$_SESSION["username"] = $username;
    	$_SESSION["password"] = $password;
    

    Checking to see if a session variable already exists:

    	if (isset($_SESSION["username"])
       		$username = $_SESSION["username"];
    	else
       		$_SESSION["username"] = $username;
    

    Deleting a session variable (enhanced security):

    	unset($_SESSION["username"]);

    Also possible to delete entire session --- see online docs.


    Example:  Counting Page Accesses

    This demonstrates a simple script which counts how many times the user has accessed pages on a website.  It maintains four session variables (on for each page on the site).  Note that the SID and the current selected page (whichPage) are passed as GET parameter.

        pageCount.php    pageCount.txt