PHP
Programming

PHP Sessions

What is PHP Sessions ?

When creating a website that requires a user to login, PHP sessions is a very useful function that allows you to store the user’s information on the server for later use. However, PHP sessions is only temporary and will be delete once a user leaves the website. For example, you will need the user to login to maintain his identity on the website.

On the internet, there is one issue, the HTTP address does not keep state, therefore the web server does not know who you are or what you do. This issue is resolved with session variables, which save user data for usage on various pages e.g. username, phone number and etc… Session variables typically persist until the user exits the browser.

In this article I am going to provide a few examples on how we can implement PHP sessions.

Before you can store user information, you will have to start the PHP session with this syntax : “session_start();”
Remember, the session_start(); MUST always be on top of the <html> section.
For example:

<?php session_start(); ?>
<html>
<body>
</body>
</html>

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:
Example:

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>

If you want to destroy the session, you can use either the unset() or the session_destroy() function.

<?php
unset($_SESSION['views']);
?>

Or completely destroy the session.

<?php
session_destroy();
?>

The session file will be deleted by session destroy() (if file storage is used). Unless garbage collection removes it, the session file will remain on the server. Therefore, you must call session destroy to ensure that the server’s storage of session data is destroyed.

Also take note that not every page needs to call this. Just when the user signs out and you are no longer in need of the data kept.

In Conclusion

Using PHP session, you will be able to check if the user is still logged in and also stores additional information about the user once the user logs in. Since the user’s information are stored in the session, you can retrieve it at any time as long as it is not destroyed.