What is PHP Session
The session is another way of storing the user's temporary data on the server. Unlike cookies, the session stores data on the server with a short session ID string with the data. The server sends a cookie with the string ID to the browser in response to a request. When the browser requests a page from the website, the cookie with string ID goes back to the server, and then your PHP script can access the session data.
As a developer, you specifically store the user's information on the database server to use them later in your application, but sometimes you need temporary data fields to send across the website's pages, and one way of saving temporary data is the cookie discussed in an earlier tutorial.
As we discussed, a cookie stores data on the user's computer, and hence there is a chance an attacker can manipulate the cookie by inserting malicious content to hack the website. Regardless of the request's origin, the browser sends cookies to the server with all requests. Therefore it creates a performance issue. An attacker can't access or change the session data since the PHP-generated session ID is random and unique.
Staring PHP Session
It is straightforward to start a session on PHP. You can begin by calling the function session_start(). It generates a new session with a unique SID and sends it to the browser as a cookie called PHPSESSID. If a previous session exists, then the session_start() function searches the session that belongs to the session ID and makes it available to the superglobal array $_SESSION.
Reading and Writing Session Data
The superglobal array $_SESSION is used to save the data as keys and values, and the session variables are available till the user closes the browser. You can store the user's first name as follows in the session.
User information saved."; ?> Info Pag
Then you can utilize the session data on your website's pages. In the previous example, we set the first name. You could display the first name as follows in showinfo.php file.
First Name: ".$_SESSION["first_name"].”
” ?> ?>
Destroying a PHP Session
This session_destroy function gets rid of all the session variables, and PHP does not pass the session ID number to further pages, but the current page can still access the session variables. The function does not have any argument.
To delete a particular session value, use the unset function.