PHP sessions
Even though we can store data using cookies, it has some security issues. Since cookies are stored on user's computer, it is possible for a hacker to easily modify a cookie content to insert potentially harmful data in your application that might break your application. Also every time the browser requests a URL to the server, all the cookie data for a website is automatically sent to the server within the request. It means if we have stored 5 cookies on user's system, each having 4KB in size, the browser needs to upload 20KB of data each time the user views a page, which can affect your site's performance. We can solve both of these issues by using the PHP session. A PHP session stores data on the server rather than user's computer. In a session based environment, every user is identified through a unique number called session identifier or SID. This unique session ID is used to link each user with their own information on the server like emails and posts.
Starting a PHP session
Before we can store any information in session variables, you must first start up the session. To begin a new session, simply call the PHP session_start() function. It will create a new session and generate a unique session ID for the user. The session_start() function first checks to see if a session already exists by looking for the presence of a session ID. If it finds one, it sets up the session variables and if doesn't, it starts a new session by creating a new session ID. Session variables are stored in associative array called $_SESSION[]. These variables can be accessed during lifetime of a session.
Accessing session data
Unlike cookies, you can store any types of data in sessions. We can store all your session data as key-value pairs in the $_SESSION[] super global array. The stored data can be accessed during lifetime of a session. To access the session data we recreate the session by calling session_start() and then pass the corresponding key to the $_SESSION associative array.
Destroying a session
If we want to remove certain session data, simply unset the corresponding key of the $_SESSION associative array by using the method unset( ). If we want to get rid of the whole $_SESSION[] array, we use the session_destroy( ) method. If none of the methods above are used, the $_SESSION[ ] is deleted when the user closes the browser.
1 >?php 2 session_start(); 3 4 if(isset($_SESSION["lastname"])) 5 { 6 unset($_SESSION["lastname"]); 7 } 8 session_destroy( ) ; 9 ?>
Line 6 removes the data held in $_SESSION["last name"] and Line 8 removes the full $_SESSION[ ].