Although cookies are a useful way to store data but they have some problems like
- Firstly, they are not very secure. As with form data and query strings, an attacker can easily modify a cookie’s contents to insert data that could potentially break the application or compromise security.
- Secondly, a user can store a fair amount of state information in a cookie, but all the cookie data for a Web site is sent every time the browser requests a URL on the server. If a user has stored 10 cookies, each 4KB in size, on the browser, then the browser needs to upload 40KB of data each time the user views a page!
Both of these issues can be overcome by using PHP sessions.
So rather than storing data in the browser, a PHP session stores data on the server, and associates a short session ID string (known as SID) with that data. The PHP engine then sends a cookie containing the SID to the browser to store. Then, when the browser requests a URL on the Web site, it sends the SID cookie back to the server, allowing PHP to retrieve the session data and make it accessible to the script.
The session IDs generated by PHP are unique, random, and almost impossible to guess, making it very hard for an attacker to access or change the session data. Furthermore, because the session data is stored on the server, it does not have to be sent with each browser request. This allows a user to store a lot more data in a session than in a cookie.
By default, PHP stores each session’s data in a temporary file on the server. The location of the temporary files are specified by the session.save_path directive in the PHP configuration file. A user can display this value with:
echo ini_get( “session.save_path” );
The session files are often stored in C:\WINDOWS\Temp on Windows systems.
ini_get() lets a user to access the value of most PHP configuration directives, and ini_set() lets a user to set directives.
Although a user can store a fair amount of data in a session but sessions are only designed to store temporary data relating to the user’s current interaction with the Web site. In fact, by default, PHP’s session cookies are set to expire when the browser is closed. If a user need to store data on a more permanent basis, consider storing it in files or a database.