Tutorialsplane

PHP Sessions


PHP Sessions :– A session is a way to store information (in variables) to be used across multiple pages. Unlike a cookie, the information is not stored on the users computer.

PHP sessions are stored in server directory.So php sessions are more secure than cookies because they are stored on browser.

PHP $_SESSION super global is an associative array which is used to set and get sessions variable to make their use in web pages.


Session Basics

Sessions are simply server-side cookies each with a corresponding client side cookie that contains only a reference to its server-side counterpart. When a user visits a page, the client sends the reference code to the server, and PHP will then match that reference code to a server-side cookie and load the data in the server’s cookie into the $_SESSION superglobal.

Pros

  1. Can store very large amounts of data easily.
  2. Save bandwidth by passing only a reference to the session each pageload. A client-side cookie has to pass all of its data.
  3. Data is stored on the web server. This makes sessions secure, because the data cannot be viewed or edited by the client.

Cons

  1. Ends when the browser is closed unless you’ve configured php.ini to extend sessions’ cookie lifetime. Cannot last forever.

Difference between Cookie and Session

  1. Cookies can not hold multiple variables whereas sessions can hold
  2. Cookies can store limited amount of data approximately 4 kb but sessions do not have a limitation.
  3. Cookies are less secure because anyone can access them but sessions are inaccessiable.
  4. To expire the cookie we need to set a time parameter whereas in sessions we use session_destroy() function.

PHP Sessions | Example

Example

<?Php session_start();
??>


<?Php $_SESSION["name"]="Adam";
$_SESSION["age"]="20";
echo "sessions variables are set successfully";
echo "<br?>";
?>
Get the session value


Destroying Sessions | Example

Example//getsession.php

<?Php session_start();
??>


<?Php $_SESSION["name"]="Adam";
$_SESSION["age"]="20";
echo "sessions variables are set successfully";
echo "<br?>";
?>
<?Php session_unset();
session_destroy();
??>
Get the session value


PHP Tutorial