Home arrow PHP arrow Page 3 - Couch Sessions

The First Session - PHP

Need to build an online shopping cart in a hurry? This articletakes a look at session management, an important component oftransaction-based Web sites, and explains the fundamentals of addingsession support to your site. Examples in PHP4 and PHP3 with PHPLib.

  1. Couch Sessions
  2. Stateless In Seattle
  3. The First Session
  4. But There's More Than One Way To Skin A Cat...
By: Vikram Vaswani and Harish Kamath, (c) Melonfire
Rating: starstarstarstarstar / 2
May 02, 2000

print this article


One of the standard examples used to demonstrate how a session works is the hit counter application - this is a simple session-based counter that initializes a variable the first time you visit a Web page, and increments it each time you reload the page. Take a look at the code:

<?php // initialize a session session_start(); // register a session variable session_register('counter'); ?>
Every session in PHP4 begins with a call to the session_start() function; this function checks to see whether a session already exists, and creates one if it doesn't. Next, the session_register() function is used to register the variables that will exist throughout the session - in the example above, the variable is called "counter", and has been initialized with no value whatsoever.

Now, let's add a couple of additional lines to the example above, and the hit counter will begin working as advertised:

<?php // initialize a session session_start(); // register a session variable session_register('counter'); // increment and display the value of the counter $counter++; echo("You have visited this page $counter times! Don't you have anything else to do, you bum?!"); ?>
Go on - try it out! Each time you reload the page, the value of the counter will increase, illustrating how the value of the variable is preserved in the session.

How does this happen? Well, each time a session is initiated, a session cookie [called PHPSESSID] is created on the client system, and is assigned a randomly-generated number; at the same time, a similar entry is created on the server containing the values of the variables registered during the session. This correspondence between the server and the client, with the session id as the common denominator, makes it possible to store the values of different variables throughout the session.{mospagebreak title=Playing The Market} Now that you've got the basics down, how about something a little more complex, just to demonstrate a real-world application of sessions. Let's assume that we have a financial portal, which allows its users to select four stocks and then displays the current market price of those stocks on each and every page that the user visits in his journey through the site.

In the example below, we're assuming that the user has already been authenticated and logged in to the Web site. A MySQL database, containing a "user_info" table, is used to store the user's four stocks together with his unique username. Once a session has been initiated, we register variables to store the values of the username and the four stocks, and then connect to the database to retrieve these values and display them on the page.

The code might look something like this:

<?php //initiate a session session_start(); // register the session variables // username session_register('username'); // variables for selected stocks session_register('stock1'); session_register('stock2'); session_register('stock3'); session_register('stock4'); // connect to MySQL $db = mysql_connect("someserver.com", "tom", "jones"); // select database on MySQL server mysql_select_db("stock_db", $db); // query database using SQL $query = "select stock_pref1,stock_pref2,stock_pref3,stock_pref4 from user_info where username='$username'"; $result = mysql_query($query,$db); // get stock symbols from database // and assign to session variables list($stock1,$stock2,$stock3,$stock4) = mysql_fetch_row($result); echo "Hi $username!<br>"; echo "Your selected stocks are:<br>"; echo "$stock1<br>"; echo "$stock2<br>"; echo "$stock3<br>"; echo "$stock4<br>"; // code to generate rest of page ?>
PHP4 comes with numerous other session-related functions - most of them are self-explanatory, and are listed below.

Destroy all session data [this comes in very useful when a user logs out of a site and you need to destroy all the variables created during his visit]

Set or read the current session name

Set or read the current session id

De-register variables from a particular session.

Checks whether or not a session variable has already been registered. For example,

<?php session_start(); if(session_is_registered(username)) { echo "A session variable by the name \"username\" already exists"; } else { echo "No variable named \"username\" registered yet. Registering..."; session_register(username); } ?>
session_encode() and session_decode()
Encodes and decodes session data as a string. Here's how you could use them:

<?php session_start(); session_register('someString'); $someString="I hate cats!"; // encode all the session variables into a single string $sessStr = session_encode(); // which can be seen here echo $sessStr; echo "<br><br>"; // replace any appearance of cats with dogs $sessStr = ereg_replace("cats","dogs",$sessStr); // update session variables after decoding session_decode($sessStr); // and display it again echo $sessStr; ?>
Finally, before we get to PHPLIB, there's one technical issue you should be aware of - all the examples above use cookies to store the session id on the client. But what happens if the client browser is set to reject cookies?

>>> More PHP Articles          >>> More By Vikram Vaswani and Harish Kamath, (c) Melonfire

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: