In general, session refers to lớn a frame of communication between two medium. A PHP session is used lớn store data on a server rather than the computer of the user. Session identifiers or SID is a chất lượng number which is used khổng lồ identify every user in a session based environment. The SID is used to link the user with his information on the server like posts, emails etc.
Bạn đang xem: Creating, destroying, and working with session in php
How are sessions better than cookies?
Below are different steps involved in PHP sessions:Starting a PHP Session: The first step is to start up a session. After a session is started, session variables can be created to lớn store information. The PHP session_start() function is used lớn begin a new session.It also creates a new session ID for the user.
Below is the PHP code to lớn start a new session:
Storing Session Data: Session data in key-value pairs using the $_SESSION<> superglobal array.The stored data can be accessed during lifetime of a session.
Below is the PHP code lớn store a session with two session variables Rollnumber và Name:
Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling session_start() and then by passing the corresponding key khổng lồ the $_SESSION associative array.
The PHP code lớn access a session data with two session variables Rollnumber and Name is shown below:
The Name of the student is :Ajay The Roll number of the student is :11Destroying Certain Session Data: lớn delete only a certain session data,the unset feature can be used with the corresponding session variable in the $_SESSION associative array.
The PHP code khổng lồ unset only the “Rollnumber” session variable from the associative session array:
Destroying Complete Session: The session_destroy() function is used to lớn completely destroy a session. The session_destroy() function does not require any argument.