codescracker


php

PHP Sessions



« Previous Tutorial Next Tutorial »


A session is basically a way to store the information (in variables) to be used across the multiple pages.

PHP5 Sessions

Unlike cookie, the information are not stored on the user's computer.

Session is just like, when you work with an application, means you opened the application, done some changes, and then you closed it. This is much like a session.

Start PHP Session

A session is started with the function named session_start(). Session variables are set with the PHP global variable named $_SESSION

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
$_SESSION["favcolor"] = "green";
$_SESSION["favfruit"] = "mango";
echo "Session variables are set.";
?>

</body>
</html>

Get PHP Session Variable Values

Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php")

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite fruit is " . $_SESSION["favafruit"] . ".";
?>

</body>
</html>

Following is an another way to show all the session variable values for a user session :

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

Delete a PHP Session

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
session_unset(); 
session_destroy(); 
?>

</body>
</html>

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test