How To Create, Access And Destroy Sessions In Php

What is a session?In general, session refers lớn a frame of communication between two medium. A PHP session is used to lớn store data on a hệ thống rather than the computer of the user. Session identifiers or SID is a unique number which is used lớn 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: How to create, access and destroy sessions in php

How are sessions better than cookies?Although cookies are also used for storing user related data, they have serious security issues because cookies are stored on the user’s computer and thus they are mở cửa to attackers lớn easily modify the content of the cookie.Addition of harmful data by the attackers in the cookie may result in the breakdown of the application.Apart from that cookies affect the performance of a site since cookies send the user data each time the user views a page.Every time the browser requests a URL to lớn the server, all the cookie data for that trang web is automatically sent to lớn the server within the request.
Below are different steps involved in PHP sessions:Starting a PHP Session: The first step is to lớn 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 khổng lồ begin a new session.It als 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 to lớn store a session with two session variables Rollnumber & Name:

Xem thêm: Ứng Dụng Zenly Là Gì - Chế Độ Tàng Hình Là Gì

Accessing Session Data: Data stored in sessions can be easily accessed by firstly calling session_start() và then by passing the corresponding key lớn the $_SESSION associative array.The PHP code to access a session data with two session variables Rollnumber và Name is shown below:
Output:The Name of the student is :Ajay The Roll number of the student is :11Destroying Certain Session Data: to 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 lớn completely destroy a session. The session_destroy() function does not require any argument.