Storing non-sensitive data the smart way through PHP sessions

The topic of data storage is very broad and complex, yet here we’re looking to cover a very particular case. Namely, a situation in which, for instance, you may wish to store a user’s preferences or the secret word displayed in a CAPTCHA image for future reference or usage. You can accomplish that easily by using PHP sessions.

Why choose PHP sessions in favor of cookies?

By now, you have probably started wondering why you might want to bother with PHP sessions to store such information, when you can do it the traditional way, by using cookies to store small amounts of data specific to a particular user. That is a valid concern, yet you must understand that some situations call for the use of PHP sessions in favor of cookies.

One such situation is the one where you need the data stored on the server and not your user’s browser. In this case, the session data is kept in a temporary directory located on your web server. Also, if the data is transient, and only relevant for the current browsing session, it’s wiser to opt for PHP sessions. Finally, if the data does not contain any information that requires a large degree of protection, you can store it in a PHP session.

Initializing a PHP session

At the beginning of your script, call the session_start() function. This call should be in every script that needs to utilize the session data. This function takes no parameters. As you call this function, PHP will set a cookie in your client’s browser, which contains a session identifier (“session ID”). Additionally, it will create a session data file designed to store variables relevant for that particular session.

Storing and accessing the variables

In order to store variables related to the session, you must simply assign a name of your choice to a  member of the $_SESSION array. For example:

$_SESSION["secretword"] = "SCR" ;
$_SESSION["theme"] = "blue" ;

To access any of these variables, reference it as you would with any PHP array. The function strcmp() is used to compare the contents of the two variables.

$captcha = $_POST["captcha"] ;
$secretword = $_SESSION["secretword"] ;

if (strcmp( $captcha, $secretword )) {
// it's a bot
else {
// matched -- it's a human

For ending a session, PHP provides the session_destroy() function to destroy the data associated with a session. But since that function does not remove everything, you may have to manually remove the cookie, by using the usual method one uses to delete a cookie in PHP.

And that is how you can use PHP sessions to store non-sensitive data. We hope this guide proves useful to you!

Leave a Reply