PHP Sessions
0 4186
PHP Session is used to make data accessible across the multiple pages of a whole website. A session generates a file in a temporary directory on the server, where registered session variables and their values are stored.
This data will be obtainable to all the web pages on the site at the time of the visit.
The location of the temporary file is specified by a setting in the php.ini file known as session.save_path
Before, using any session variable ensure you have set this path.
When a session is initiated following things occur -
PHP first generates a unique identifier for that specific session, which is a random thread of 32 hexadecimal numbers like as 3c7foj34c3jj973hjkop2fc937e3443.
A cookie named PHPSESSID is automatically referred to the user's computer to save a unique session recognition string.
A file is automatically built on the server in the elected temporary directory and bears the name of the unique identifier predetermined by sess_ ie sess_3c7foj34c3jj973hjkop2fc937e3443.
When a PHP script needs to retrieve the value of a session variable, PHP gets the unique session identifier thread from the PHPSESSID cookie and then seems in its temporary file for the file bearing that name and a justification can be accomplished by comparing both values.
A session stops when the user loses the web browser or after leaving the website, the server will end the session after a prefixed duration, commonly 30 minutes time period.
Starting a PHP Session
A PHP session is simply started by creating a call to the session_start() function.This function first observes, if a session is already started or not, then it starts one. It is prefer to put the call to session_start() at the start of the page.
Session variables are stored in the associative array which is called $_SESSION[]. These kinds of variables can be accessed during the lifetime of a session.
If you want to use the information across multiple pages, Session is used for this.
A session works with 'start' function and ends with 'destroy' function.
For example: There is a page, 'index.php' and the coding is:
<?php // Firstly, start the session session_start(); //Now set the variable $_SESSION['username'] = "Vihaan"; $_SESSION['id'] = "1"; ?>
Now there is another page: 'home.php'
To get the username you have to start the session-variable on the every page.
<?php
session_start();
echo "HELLO!" . "<br>" . "My name is" . $_SESSION["username"];
?>
To end the Session: 'end.php'
<?php
session_start();
session_unset();
session_destroy();
?>
Share:
Comments
Waiting for your comments