Start a PHP Session


Start a PHP Session


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let's create a new page called "session1.php". In this page, we start a new PHP
session and set some session variables:
Example:

<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";

echo "Session variables are set.";
?>
</body>
</html>

Output:
Session variables are set.

Get PHP Session Variable Values

Next, we create another page called "session3.php". From this page, we will access the
session information we set on the first page ("session2.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
Also notice that all session variable values are stored in the global $_SESSION variable:
Session3.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body>
</html>

OUTPUT:
Favorite color is blue.
Favorite animal is dog.
Another way to show all the session variable values for a user session is to run the
following code:-

Session2.php
Example:

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

<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>

Output:
Array ( [favcolor] => blue [favanimal] => dog )
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body></html>

Output: Session is destroy

Custom Search

%d bloggers like this: