Using session in PHP

Keeping in mind the fact that Internet is a stateless platform and every request for a web page is treated as unique, there is a serious need of a tool to maintain the state. Otherwise, it will be a messy situation to keep track of requests made by a particular user. The good news is that use of PHP session serves the solution to this problem. This session variable is of great importance for web applications like shopping carts and is considered as equivalent to cookies, other significant way of maintaining the state.

What Is PHP Session Capable Of

PHP session is capable of storing the information in the form of session variables, in order to handle the ever-increasing traffic on a website. For instance, consider a shopping website, with products scattered in different categories and different pages. In such a situation, a user may switch from one page t another and keep on adding products from different pages to his or her shopping cart.

Memcache

Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

The Memcache module also provides a session handler (memcache).

More information about memcached can be found at » http://www.danga.com/memcached/.

Below is one example


$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");

$version = $memcache->getVersion();
echo "Server's version: ".$version."
\n";

$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;

$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)
\n";

$get_result = $memcache->get('key');
echo "Data from the cache:
\n";

var_dump($get_result);

?>