What is the use of session in php?
Session handling is a key concept in PHP that enables user information to be persisted across all the pages of a website or app. In this post, you'll learn the basics of session handling in PHP. Show
We'll start with an explanation of how sessions work and how they are related to cookies. Then we'll look at a few code snippets that demonstrate how to work with sessions. You'll learn how to create and destroy sessions, and how to change session variables. Cookies vs. Session VariablesNot sure if you need cookies or session variables? Session variables are a way to store data about a user in a database and retrieve it later. Cookies are a way to store data about a user on the user's computer. Session variables are typically used in applications that need to keep track of a user's activity. Cookies are typically used in applications that need to store information about a user for a single site. You can also learn about session variables in my post on using cookies in PHP. What Is a Session in PHP?A session is a mechanism to persist information across different web pages to identify users as they navigate a site or app. Are you wondering why sessions are needed for a website? To see why sessions are necessary, we have to go back and see how the HTTP protocol is designed to work. The HTTP protocol is a stateless protocol, which means that there's no way a server can remember a specific user between multiple requests. For example, when you access a web page, the server is just responsible for providing the contents of the requested page. So when you access other pages of the same website, the web server interprets each and every request separately, as if they were unrelated to one another. There's no way for the server to know that each request originated from the same user. The following diagram depicts the HTTP protocol in a nutshell. In this model, if you wanted to display user-specific information, you'd have to authenticate a user in each request. Imagine if you had to type your username and password on every page that displayed your profile information! Yes, it would be cumbersome and not practical at all, and that's where sessions come into the picture. A session allows you to share information across different pages of a single site or app—thus it helps maintain state. This lets the server know that all requests originate from the same user, thus allowing the site to display user-specific information and preferences. Login Flow With Sessions and CookiesLet's quickly go through a common login flow for a website to understand what happens behind the scenes.
In this way, the user data is preserved across multiple requests, and the user is kept logged in throughout a session. The following diagram depicts how the HTTP protocol works with sessions. Now that you've seen a brief introduction to how sessions work, we'll create a few practical examples to demonstrate how to create and manipulate session variables. How to Start a SessionIn this section, we’ll discuss how to start a session in PHP. Whenever you want to deal with session variables, you need to make sure that a session is already started. There are a couple of ways you can start a session in PHP. Use the session_start FunctionThis is the method that you'll see most often, where a session is started by the The important thing is
that the Automatically Start a SessionIf there’s a need to use sessions throughout your application, you can also opt in to starting a session automatically without using the There’s a configuration option in the php.ini file which allows
you to start a session automatically for every request— session.auto_start = 1 On the other hand, if you don’t have access to the php.ini file, and you're using the Apache web server, you could also set this variable using the .htaccess file. php_value session.auto_start 1 If you add the above line in the .htaccess file, that should start a session automatically in your PHP application. How to Get a Session IdAs we discussed earlier, the server creates a unique number for every new session. If you want to get a session id, you can use the That should give you the current session id. The It’s important to note that the How to Create Session VariablesIn this section, we’ll explore how to initialize session variables in PHP. As we discussed earlier, once a session is started, the Let’s go through the following example script that demonstrates how to initialize session variables. As you can see, we’ve started a session at the beginning of the script using the When you store the data in a session using the As we discussed, the session information is shared across requests, and thus the session variables initialized on one page can be accessed from other pages as well, until the session expires. Generally, a session expires when the browser is closed. How to Modify and Delete Session VariablesYou can modify or delete session variables created earlier in the application in the same way as for regular PHP variables. Let’s see how to modify the session variables. In the above script, we’ve checked if the On the other hand, if you would like to delete a session variable, you can use the Thus, you can no longer access the How to Destroy a SessionIn this section, we’ll see how you could destroy a session. In the previous section, we discussed the The So if you're using the Session HandlersSo far, we've discussed how you can perform different operations with session variables. In this section, we'll discuss what a session handler is and how you can use it. A PHP session handler is a mechanism which instructs PHP how it should manage sessions. The default session handler is a file system, and it means that PHP stores sessions on the disk. Basically, it's a small file on the server which is associated with the unique session id. It's the same id which is stored in a session cookie on the client browser. The default session handler in PHP provides you with all the features that are needed, but sometimes you want to store sessions differently. For example, you might want to manage sessions in a database, Redis, or some other storage. In this case, you need to implement a custom session handler which overrides the default behavior. To understand how custom session handlers work, we'll briefly discuss how you can implement a database session handler which manages sessions in a MySQL database. How to Implement a Database Session HandlerIn the PHP session lifecycle, there are different stages like open, read, write, and close. Additionally, there are two more stages: destroy and garbage collection. So when you implement a custom session handler, you have to handle each of these stages to manage the session data properly. There are two ways you could implement a custom session handler, Either you could define callback functions for different stages in the session lifecycle or you could write a class which implements the In our example, we’re going to store sessions in the MySQL database. So let’s create a table which stores the session data by using the following snippet. CREATE TABLE `sessions` ( `session_id` varbinary(192) NOT NULL, `created` int(11) NOT NULL DEFAULT '0', `session_data` longtext COLLATE utf8mb4_unicode_ci, PRIMARY KEY (`session_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; Next, let’s see how our custom database session handler looks: connection = new mysqli("HOST_NAME","USERNAME","PASSWORD","DATABASENAME"); } public function open($savePath, $sessionName) { if ($this->connection) { return TRUE; } else { return FALSE; } } public function read($sessionId) { try { $stmt = $this->connection->prepare("SELECT session_data FROM sessions WHERE session_id = ?"); $stmt->bind_param("s", $sessionId); $stmt->execute(); $stmt->bind_result($sessionData); $stmt->fetch(); $stmt->close(); return $sessionData ? $sessionData : ''; } catch (Exception $e) { return ''; } } public function write($sessionId, $sessionData) { try { $stmt = $this->connection->prepare("REPLACE INTO sessions(`session_id`, `created`, `session_data`) VALUES(?, ?, ?)"); $stmt->bind_param("sis", $sessionId, $time=time(), $sessionData); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return FALSE; } } public function destroy($sessionId) { try { $stmt = $this->connection->prepare("DELETE FROM sessions WHERE session_id = ?"); $stmt->bind_param("s", $sessionId); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return FALSE; } } public function gc($maxlifetime) { $past = time() - $maxlifetime; try { $stmt = $this->connection->prepare("DELETE FROM sessions WHERE `created` < ?"); $stmt->bind_param("i", $past); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return FALSE; } } public function close() { return TRUE; } } Our custom session handler class public function __construct() { $this->connection = new mysqli("HOST_NAME","USERNAME","PASSWORD","DATABASENAME"); } First, to use this code, make sure to replace the public function open($savePath, $sessionName) { if ($this->connection) { return TRUE; } else { return FALSE; } } When the session is started, the public function read($sessionId) { try { $stmt = $this->connection->prepare("SELECT session_data FROM sessions WHERE session_id = ?"); $stmt->bind_param("s", $sessionId); $stmt->execute(); $stmt->bind_result($sessionData); $stmt->fetch(); $stmt->close(); return $sessionData ? $sessionData : ''; } catch (Exception $e) { return ''; } } Next,
PHP calls the public function write($sessionId, $sessionData) { try { $stmt = $this->connection->prepare("REPLACE INTO sessions(`session_id`, `created`, `session_data`) VALUES(?, ?, ?)"); $stmt->bind_param("sis", $sessionId, $time=time(), $sessionData); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return FALSE; } } When PHP needs to save or close a session, it calls the public function close() { return TRUE; } The public function destroy($sessionId) { try { $stmt = $this->connection->prepare("DELETE FROM sessions WHERE session_id = ?"); $stmt->bind_param("s", $sessionId); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return FALSE; } } The public function gc($maxlifetime) { $past = time() - $maxlifetime; try { $stmt = $this->connection->prepare("DELETE FROM sessions WHERE `created` < ?"); $stmt->bind_param("i", $past); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return FALSE; } } When PHP runs the garbage collector periodically, the Using the MySQL Session Handler ClassNow, let’s see how to
use the $objSessionHandler = new MySQLSessionHandler(); session_set_save_handler($objSessionHandler, true); session_start(); $_SESSION['favoriteWebsite'] = 'tutsplus.com'; As you can see, we just need to initialize the If everything goes well, you should see the session entry in the And with that, you’ve created a working custom session handler which manages sessions in a database! ConclusionIn this article, we’ve explored the basics of session handling in PHP. It’s a key concept which allows you to persist information across web pages. In the first half of the article, we discussed the basic concepts of sessions, and later on we created a few PHP examples to demonstrate how you could create and destroy sessions as well as manipulating session variables. A related topic is cookies. You can learn how to use cookies in PHP right here at Envato Tuts+! Did you find this post useful? Software Engineer, FSPL, India I'm a software engineer by profession, and I've done my engineering in computer science. It's been around 14 years I've been working in the field of website development and open-source technologies. Primarily, I work on PHP and MySQL-based projects and frameworks. Among them, I've worked on web frameworks like CodeIgnitor, Symfony, and Laravel. Apart from that, I've also had the chance to work on different CMS systems like Joomla, Drupal, and WordPress, and e-commerce systems like Magento, OpenCart, WooCommerce, and Drupal Commerce. I also like to attend community tech conferences, and as a part of that, I attended the 2016 Joomla World Conference held in Bangalore (India) and 2018 DrupalCon which was held in Mumbai (India). Apart from this, I like to travel, explore new places, and listen to music! What is the purpose of session in PHP?A PHP session is used to store data on a server rather than the computer of the user. Session identifiers or SID is a unique number which is used to identify every user in a session based environment.
Where session is used in PHP?PHP session is used to store and pass information from one page to another temporarily (until user close the website). PHP session technique is widely used in shopping websites where we need to store and pass cart information e.g. username, product code, product name, product price etc from one page to another.
Why do we use sessions?Sessions are a simple way to store data for individual users against a unique session ID. This can be used to persist state information between page requests. Session IDs are normally sent to the browser via session cookies and the ID is used to retrieve existing session data.
What is PHP session and how it works?PHP responds by sending a unique token that identifies the current session. This is known as the session ID. In all subsequent requests, the browser sends the session ID to say, "Hey, it's me again." All other data related to the session is stored on the web server. Only the session ID gets passed back and forth.
|