If you want to pass important information from one page to another pages or if you want to store important information like user id, password then PHP session is best option for you.
PHP session is a global variable that is stored on the server. A variable that could be used on various page, that is called session in PHP. Cookies are also worked similar to session but cookies are stored on the user computer and PHP session is not stored on user computers. Each PHP session variables have a unique ID which is used to getting session information from the server. Comparisons of cookies, Session variables have large capacity for storing information.
When you work on application, you need to use one information on various pages then PHP session variables solve this issue by storing information in session. Session variable will start when you open application and it will close automatically when you close browser by default. Otherwise you can destroy session variable by some PHP function.
Also if you need a permanent storage of variable, then you have to store the information in your database.
A session creates a temporary directory on server for storing session variable where session variable and their values are stored. A same user can use this variable during surfing on applications. The server will terminate session after 30 minutes when users are not active on application.
How to start a PHP Session?
In order to create a session in PHP, you have to call the session_start() function. All session variables are stored in the PHP global variable $_SESSION.
Note: session_start() function will be write before start a any HTML tags.
For Example:
How to retrieve PHP session value?
Remember that all session variable values are stored into global variable like $_SESSION. Here you have to mind, don’t use session_start() function after HTML tags. session_start() function will be shows before starting all HTML tags.
For example:
”;
echo "City name is " . $_SESSION["city "] ;
?>
How to modify session in PHP?
For modifying or changing session variables, just overwrite session variable.
For Example:
”;
echo "City name is " . $_SESSION["city "] ;
?>
How to destroy session in PHP or How to delete session in PHP?
For destroying session variables, we have three options.
- unset()
- session_unset()
- session_destroy()
What is the difference between session_unset() and session_destroy() ?
If you want to delete single variable, then you have to use unset() function. unset() is destroy single variable in application.
If you want to remove all session variable, then you have to use session_unset(). session_unset() function is remove all session variable.
If you want to delete all session then you have to use session_destroy() function. session_destroy() is destroy all session from whole application.
For example:
For more details about session, visit: PHP Session