What is a PHP Session?
When you work on your computer you run the application open it, make the changes and then close it. This is called one session that user has performed on the particular application. But on the internet storing such data is difficult.
This is where the session comes in place. The user sessions last until the user closes the browser. You can store the username, favorite color etc as a variable value in the sessions. The session variable holds the information about the one single user and runs through all the pages in one application.
Start a PHP Session
Use php session_start()
function to start the session. The session variables are set with the php global variable $_SESSION
Example:
[php]<?php
// Start the session
session_start();
?>[/php]
[php]<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>[/php]
Code Example:
First, we have set the session by using session_set()
function.
[php]<?php
session_start();
?>[/php]
Then in the HTML, we have to use the global session variable $_SESSION
to set the two session values “favcolor
” and “favanimal
” which has value green and cat respectively.
Destroy a PHP Session
To delete all global session variables use the session_unset()
and session_destroy()
functions to delete the session.