Session_start(): Failed to Read Session Data: User
Read Time: 14 mins Languages:
Session handling is a key concept in PHP that enables user information to exist persisted across all the pages of a website or app. In this post, you'll learn the nuts of session treatment in PHP.
We'll beginning 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 Variables
Not certain if y'all need cookies or session variables? Session variables are a manner to store data about a user in a database and retrieve it later. Cookies are a fashion to shop data virtually a user on the user's computer. Session variables are typically used in applications that need to keep track of a user'due south activity. Cookies are typically used in applications that need to store information nigh a user for a single site.
You tin also learn about session variables in my mail service on using cookies in PHP.
What Is a Session in PHP?
A session is a machinery to persist information across unlike web pages to identify users equally they navigate a site or app. Are you wondering why sessions are needed for a website? To see why sessions are necessary, nosotros take to go back and see how the HTTP protocol is designed to work.
The HTTP protocol is a stateless protocol, which means that in that location'south no manner 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 lot access other pages of the same website, the web server interprets each and every request separately, equally if they were unrelated to one another. In that location's no style 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, y'all'd accept to cosign a user in each request. Imagine if you had to type your username and countersign on every page that displayed your profile information! Yep, it would be cumbersome and not practical at all, and that's where sessions come into the moving picture.
A session allows y'all to share information beyond dissimilar pages of a single site or app—thus it helps maintain state. This lets the server know that all requests originate from the aforementioned user, thus allowing the site to display user-specific data and preferences.
Login Flow With Sessions and Cookies
Permit'due south quickly become through a common login flow for a website to understand what happens behind the scenes.
- A user opens the login page of a website.
- Afterward submitting the login course, a server on the other end authenticates the asking by validating the credentials that were entered.
- If the credentials entered by the user are valid, the server creates a new session. The server generates a unique random number, which is called a session id. It also creates a new file on the server which is used to store the session-specific information.
- Next, a session id is passed back to the user, along with whatever resource was requested. Behind the scenes, this session id is sent in the
PHPSESSID
cookie in the response header. - When the browser receives the response from the server, information technology comes across the
PHPSESSID
cookie header. If cookies are allowed by the browser, information technology volition save thisPHPSESSID
cookie, which stores the session id passed by the server. - For subsequent requests, the
PHPSESSID
cookie is passed back to the server. When the server comes across thePHPSESSID
cookie, it volition try to initialize a session with that session id. It does so past loading the session file which was created before, during session initialization. It will then initialize the super-global array variable$_SESSION
with the data stored in the session file.
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 Session
In this section, nosotros'll discuss how to start a session in PHP.
Whenever you want to deal with session variables, you need to make certain that a session is already started. At that place are a couple of ways you tin commencement a session in PHP.
Use thesession_start
Function
This is the method that you'll see most often, where a session is started by thesession_start
part.
<?php // kickoff a session session_start(); // manipulate session variables ?>
The important thing is that thesession_start
function must be called at the beginning of the script, before any output is sent to the browser. Otherwise, yous'll encounter the infamousHeaders are already sent
error.
Automatically Start a Session
If at that place's a need to employ sessions throughout your application, you can also opt in to starting a session automatically without using thesession_start
function.
There'south a configuration option in thephp.ini file which allows you to start a session automatically for every asking—session.auto_start
. By default, it'southward set to0
, and you can set it to1
to enable the machine startup functionality.
session.auto_start = ane
On the other hand, if you don't have access to thephp.ini file, and you're using the Apache spider web server, you could besides gear up this variable using the.htaccess file.
php_value session.auto_start 1
If you add the above line in the.htaccess file, that should showtime a session automatically in your PHP application.
How to Become a Session Id
Equally nosotros discussed before, the server creates a unique number for every new session. If you want to get a session id, you lot tin use thesession_id
function, equally shown in the post-obit snippet.
<?php session_start(); echo session_id(); ?>
That should requite you the current session id. Thesession_id
part is interesting in that it can too take i argument—a session id. If yous want to supervene upon the arrangement-generated session id with your own, you can supply it to the first argument of thesession_id
role.
<?php session_id(YOUR_SESSION_ID); session_start(); ?>
It's of import to note that thesession_id
function must be placed before thesession_start
call when you lot want to kickoff a session with a custom session id.
How to Create Session Variables
In this department, we'll explore how to initialize session variables in PHP.
As nosotros discussed before, once a session is started, the$_SESSION
super-global array is initialized with the corresponding session data. By default, it's initialized with a blank array, and y'all tin store more than information past using a key-value pair.
Permit's go through the following example script that demonstrates how to initialize session variables.
<?php // get-go a session session_start(); // initialize session variables $_SESSION['logged_in_user_id'] = '1'; $_SESSION['logged_in_user_name'] = 'Tutsplus'; // access session variables repeat $_SESSION['logged_in_user_id']; echo $_SESSION['logged_in_user_name']; ?>
As yous can run into, we've started a session at the starting time of the script using thesession_start
function. Post-obit that, nosotros've initialized a couple of session variables. Finally, we've accessed those variables using the$_SESSION
super-global.
When you store the data in a session using the$_SESSION
super-global, it's eventually stored in a respective session file on the server which was created when the session was started. In this way, the session information is shared across multiple requests.
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 airtight.
How to Alter and Delete Session Variables
You lot can modify or delete session variables created earlier in the application in the same style as for regular PHP variables.
Let's see how to modify the session variables.
<?php session_start(); if (!isset($_SESSION['count'])) { $_SESSION['count'] = 1; } else { ++$_SESSION['count']; } echo $_SESSION['count']; ?>
In the above script, nosotros've checked if the$_SESSION['count']
variable is set in the first place. If it's not set, we'll ready it to1
, otherwise we'll increment it by1
. So, you if refresh this page multiple times, you should see that the counter is incremented by one every time!
On the other hand, if you would similar to delete a session variable, you can apply theunset
function, as shown in the following snippet.
<?php // start a session session_start(); // initialize a session variable $_SESSION['logged_in_user_id'] = '1'; // unset a session variable unset($_SESSION['logged_in_user_id']); ?>
Thus, you can no longer access the$_SESSION['logged_in_user_id']
variable equally information technology's deleted by theunset
function. And so that'southward how y'all tin can modify the session information.
How to Destroy a Session
In this section, we'll see how you could destroy a session. In the previous section, we discussed theunset
function, which is used if you lot want to delete specific session variables. On the other manus, if you want to delete all session-related data at one time, you can use thesession_destroy
function.
Thesession_destroy
part deletes everything that's stored in the current session. Having said that, information technology doesn't unset global variables associated with the session or unset the session cookie.
So if you lot're using thesession_destroy
function to log a user out, you must unset the $_SESSION
variable and unset the session cookie besides. Thus, the recommended way to destroy a session completely is:
<?php // start a session session_start(); // destroy everything in this session unset($_SESSION); if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"],$params["httponly"]); } session_destroy(); ?>
Session Handlers
So far, we've discussed how you can perform dissimilar operations with session variables. In this department, we'll discuss what a session handler is and how yous 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 organization, and it means that PHP stores sessions on the disk. Basically, it's a minor 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 yous 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 example, you need to implement a custom session handler which overrides the default behavior.
To understand how custom session handlers work, nosotros'll briefly talk over how you lot can implement a database session handler which manages sessions in a MySQL database.
How to Implement a Database Session Handler
In the PHP session lifecycle, there are different stages like open, read, write, and shut. Additionally, there are two more stages: destroy and garbage collection. So when you implement a custom session handler, you take to handle each of these stages to manage the session data properly.
At that place are two ways you could implement a custom session handler, Either you lot could define callback functions for unlike stages in the session lifecycle or y'all could write a form which implements the SessionHandlerInterface
interface. In both cases, you demand to employ thesession_set_save_handler
function to initialize your custom session handler. In our case, we'll use theSessionHandlerInterface
interface implementation.
In our case, nosotros're going to store sessions in the MySQL database. So permit's create a table which stores the session data past using the following snippet.
CREATE Table `sessions` ( `session_id` varbinary(192) NOT Null, `created` int(xi) Not Nix DEFAULT '0', `session_data` longtext COLLATE utf8mb4_unicode_ci, PRIMARY Key (`session_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Next, allow'southward see how our custom database session handler looks:
<?php form MySQLSessionHandler implements SessionHandlerInterface { private $connection; public function __construct() { $this->connection = new mysqli("HOST_NAME","USERNAME","PASSWORD","DATABASENAME"); } public office open($savePath, $sessionName) { if ($this->connection) { return TRUE; } else { return Simulated; } } public office read($sessionId) { endeavor { $stmt = $this->connection->ready("SELECT session_data FROM sessions WHERE session_id = ?"); $stmt->bind_param("s", $sessionId); $stmt->execute(); $stmt->bind_result($sessionData); $stmt->fetch(); $stmt->close(); render $sessionData ? $sessionData : ''; } take hold of (Exception $eastward) { return ''; } } public office write($sessionId, $sessionData) { try { $stmt = $this->connection->gear up("Supercede INTO sessions(`session_id`, `created`, `session_data`) VALUES(?, ?, ?)"); $stmt->bind_param("sis", $sessionId, $time=fourth dimension(), $sessionData); $stmt->execute(); $stmt->close(); render TRUE; } take hold of (Exception $e) { return FALSE; } } public function destroy($sessionId) { effort { $stmt = $this->connection->set up("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; endeavor { $stmt = $this->connexion->prepare("DELETE FROM sessions WHERE `created` < ?"); $stmt->bind_param("i", $past); $stmt->execute(); $stmt->close(); return True; } catch (Exception $eastward) { return FALSE; } } public function shut() { return TRUE; } }
Our custom session handler courseMySQLSessionHandler
implements theSessionHandlerInterface
interface. Thus, it must implement methods that are declared in theSessionHandlerInterface
interface. Nosotros'll look at these methods one by i to understand how each i works.
public function __construct() { $this->connection = new mysqli("HOST_NAME","USERNAME","Countersign","DATABASENAME"); }
Beginning, to use this code, make sure to supersede theHOST_NAME
,USERNAME
, and other placeholders with bodily values in the__construct
method.
public function open($savePath, $sessionName) { if ($this->connection) { return True; } else { return FALSE; } }
When the session is started, theopen
method is called. It returnsTRUE
if the database connection was successful. If there was any problem setting upwardly the database connection, information technology returnsFaux
.
public function read($sessionId) { try { $stmt = $this->connection->fix("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 $eastward) { return ''; } }
Next, PHP calls theread
method to read the session data. Theread
method receives the session id as the first argument. We'll check if in that location'south any entry available for this session id in thesession_data
tabular array. If it exists, we'll return the session data; otherwise, an empty string will be returned.
public part write($sessionId, $sessionData) { try { $stmt = $this->connection->prepare("Replace INTO sessions(`session_id`, `created`, `session_data`) VALUES(?, ?, ?)"); $stmt->bind_param("sis", $sessionId, $time=fourth dimension(), $sessionData); $stmt->execute(); $stmt->close(); render True; } catch (Exception $e) { return Imitation; } }
When PHP needs to salve or close a session, information technology calls thewrite
method. Information technology's used to write the session data in a database. We've used theReplace
syntax to make certain that if an entry exists, it volition be updated; otherwise, it'll be inserted.
public function close() { return Truthful; }
Theclose
method is called after the sessionwrite
method has been called. It works similar to a destructor in classes. In our case, there is nil particular that needs to be washed in theclose
method.
public role destroy($sessionId) { endeavor { $stmt = $this->connectedness->prepare("DELETE FROM sessions WHERE session_id = ?"); $stmt->bind_param("s", $sessionId); $stmt->execute(); $stmt->shut(); render True; } take hold of (Exception $eastward) { render Imitation; } }
Thedestroy
method is called when the session is destroyed with either thesession_destroy
orsession_regenerate_id
function. In this method, the session data is deleted from a database if information technology exists.
public function gc($maxlifetime) { $past = fourth dimension() - $maxlifetime; endeavor { $stmt = $this->connectedness->set up("DELETE FROM sessions WHERE `created` < ?"); $stmt->bind_param("i", $by); $stmt->execute(); $stmt->close(); return TRUE; } catch (Exception $e) { return Imitation; } }
When PHP runs the garbage collector periodically, thegc
method is called. The$lifetime
variable holds the value of thesession.gc_maxlifetime
configuration selection in thephp.ini file. In this method, we'll delete all sessions that are expired as a function of the garbage collection procedure.
Using the MySQL Session Handler Course
Now, permit'south encounter how to use theMySQLSessionHandler
handler class.
$objSessionHandler = new MySQLSessionHandler(); session_set_save_handler($objSessionHandler, true); session_start(); $_SESSION['favoriteWebsite'] = 'tutsplus.com';
Every bit you lot can see, we only need to initialize theMySQLSessionHandler
class and laissez passer it to thesession_set_save_handler
role to instruct PHP that it needs to use theMySQLSessionHandler
class for session management. Side by side, we've called thesession_start
office to start a session. Finally, nosotros've initialized a session variable for testing purposes.
If everything goes well, you should run across the session entry in thesessions
table every bit shown in the post-obit screenshot.
And with that, yous've created a working custom session handler which manages sessions in a database!
Conclusion
In this article, nosotros've explored the nuts of session handling in PHP. It's a key concept which allows you to persist data beyond web pages.
In the beginning half of the article, we discussed the basic concepts of sessions, and afterward 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+!
Source: https://code.tutsplus.com/tutorials/how-to-use-sessions-and-session-variables-in-php--cms-31839
Enviar um comentário for "Session_start(): Failed to Read Session Data: User"