PHP Session

In PHP Session, information or data is stored on the server side. Each session is associated with sessionID. PHP Session is created using $_SESSION variable and start with session_start() function. Session also overcomes many drawbacks related with the Cookies like Cookies are not much secure as using form data and query strings.

Any hacker can easily change a cookie's contents in order to destroy your application and even affect your hardware badly while in case of a session, SIDs generated by PHP are unique and impossible to guess or access and hence it is very difficult for a hacker to access and affect the session data. You can store more data in a session as compared to a cookie.

How to Create a PHP Session

Syntax

session_start();
$_SESSION["variablename"] = "Value";

Set the Variable in a PHP Session

Syntax

$_SESSION["variablename"] = "value";

Set PHP Variable in Session Example

<?php
session_start();
$_SESSION["yourname"] = "John";
?> 

Display Value of Variable in a PHP Session

Syntax

echo $_SESSION["variablename"];

Display Session Variable Value Example

<?php
session_start();
$_SESSION["yourname"] = "John";
echo $_SESSION["yourname"];
?> 

This will produce following result

John

Change Value of Variable in a PHP Session

Syntax:

$_SESSION["variablename"]="value1";
$_SESSION["variablename"]="value2";

Change Value of Variable in a Session Example

<?php
session_start();
$_SESSION["yourname"] = "John";
echo $_SESSION["yourname"];
$_SESSION["yourname"] = "Bob";
echo $_SESSION["yourname"];
?> 

This will produce following result

John
Bob

Remove Variables in a PHP Session

Syntax

session_unset()";

Remove Variables in a Session Example

<?php
session_start();
$_SESSION["yourname"] = "John";
session_unset();
?> 

Destroy a Session

Syntax

session_destroy();

Destroy a Session Example

<?php
session_start();
$_SESSION["yourname"] = "John";
session_unset();
session_destroy();
?>