PHP Sessions

pradeep's Avatar author of PHP Sessions
This is an article on PHP Sessions in PHP.
Building web applications with membership management is one of the most frequent tasks that every programmer does. Managing membership data, such as username, password and the member's profile with sessions in PHP is the easiest and simplest solution.

Sessions stores data about a particular user that you need on all of the pages in a variable and access it from any page. Using sessions you could hold data about particular user and access that info on all the pages as long as the user is active on the site.

Each session holds different values for different user. Sessions automatically die when the user's session is over or he closes his browser.

PHP's session-handling features, was first introduced in the 4.0 release, Sessions are native and thus require no additional packages.

To work with Sessions we will be using session_start() and session_register() functions, its important that you add sesions_start to every page where you would like to use sessions.
session1.php
PHP Code:
<?
 // create a new session
 session_start();
 
 // register a session-variable
 session_register("color"); //we have created a session with name color
 
 $color = "blue"; //assigning some value to our session
 ?>
Okay now we have created a session with name color and assigned it as blue, now in our second program (session2.php) we access the value of our session color.
session2.php

PHP Code:
<?
 session_start();
 
 echo "The value stored in your session: " $color; //retriving value from the session
 ?>
To delete a session variable we use the function session_unregister() so to delete our session color we would use the code.
PHP Code:
<?
 session_unregister(color);
 ?>
This was a very simple tutorial, we can use sessions more effectively.
Happy Coding.
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
To determine the validity of session in each page you can use

Quote:
Originally Posted by coderzone
PHP Code:
if(isset($_SESSION['ArrayName']))
{
  
//Valid session
}
else
{
  
//Invalid session

0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Correct!
But before doing that you must invoke the function
PHP Code:
session_start();