It is a way to store data for users against a session ID. Web Server has no idea who you are, has no idea whether you are logged in or you have the permissions to check this page because HTTP address doesn’t maintain state.
And by storing user’s information to be used across multiple pages Session Variables solves the problem. For Example User’s Name. Session variables ends until user closes the browser.
You can store all your data in database if you want a Permanent Storage.
Start Session
Starts with the session_start( ) function.
Variables are stored with PHP global variable $_SESSION.
Creating a new page
<?php // start session session_start(); // this session_start(); function should be first before any other html tags. ?> <!DOCTYPE html> <html> <body> <?php // set session variables $_SESSION["favfood"] = "sandwich"; $_SESSION["favcolor"] = "black"; echo "Session Variables Are Set."; ?> </body> </html>
Output :
Session Variable Values
Now lets create another page. We will access the session information we stored on our first page from this new page.
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // echo session variables that were set on previous page echo "Favorite Food Is " . $_SESSION["favfood"] . ".<br>"; echo "Favorite Color Is " . $_SESSION["favcolor"] . "."; ?> </body> </html>
Output :
Modify Session Variable
Simply overwrite it to modify session variable.
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // to change a session variable, just overwrite it $_SESSION["favcolor"] = "Maroon"; print_r($_SESSION); ?> </body> </html>
Output :
Destroy Session
Use session_unset() and session_destroy() to destroy it.
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php // remove all session variables session_unset(); // destroy the session session_destroy(); echo "All session variables are removed & Session is destroyed." ?> </body> </html>
Output :
i really don’t understand this sessions any help?