How to Use PHP Sessions in WordPress (A Step-by-Step Guide)

PHP sessions are a great way to track and store user-specific information within a PHP application. But if you’re starting from square one, you might wonder how to properly implement sessions without causing conflicts. In this article, we’ll show you how to use PHP sessions in a WordPress theme. 

Why Are PHP Sessions Useful?

Tracking and storing user session data in a WordPress PHP application has several benefits, including:

  1. php sessions in wordpressMaintaining User State: Sessions allow websites to remember user-specific data as they navigate through different pages. This is helpful for logged-in users, keeping them authenticated without requiring re-login on every page.
  2. Personalized User Experience: Websites can use PHP sessions to store user preferences, creating a more customized experience.
  3. Shopping Cart Functionality: E-commerce sites often use sessions to track shopping cart contents before checkout, ensuring that items remain in the cart even if the user navigates away from the page.
  4. Form Handling & Data Retention: PHP sessions can store user inputs temporarily, preventing data loss if a form submission fails or if the user accidentally refreshes the page.
  5. Access Control & Role Management: Certain content may be restricted to specific user roles. Sessions help manage permissions and ensure users only access authorized content..
  6. Reducing Database Queries: Instead of constantly querying the database for user-specific information, PHP sessions can store frequently accessed data, improving performance and reducing server load.
  7. Tracking User Activity: Sessions allow developers to monitor interactions such as page visits, time spent on a site, or actions taken, which can be useful for analytics, debugging, or improving user experience.

Starting a WordPress PHP Session the Right Way

 If you’re working with WordPress, you might be tempted to start a session by adding the session_start function at the very top of the PHP script. This may tempt you to add something like the following: 

<?php session_start(); ?>
<!DOCTYPE html>
<head> ….

While this approach technically works, it’s not the most efficient method in a WordPress environment. Instead, leveraging WordPress’s built-in Actions API ensures better performance and compatibility.

We’ll be adding all session-handling code to the very top of our theme’s functions.php file.

1. Use the init action hook to start the session.

WordPress provides an init action, which is the ideal place to initialize sessions. We hook a function called start_session to this action:

add_action(‘init’, ‘start_session’, 1);

2. Create the start_session function.

Before starting a new session, we first check if one is already active using session_id. This prevents session conflicts and redundant calls:

function start_session() {
if(!session_id()) {
session_start();
}
}

Ending  PHP Sessions in WordPress

PHP provides a built-in function called session_destroy that will handle clearing out all session data. However, when to call this function can be tricky to handle depending on the application. WordPress, however, provides a few ways for us to manage this in the Actions API:

1. Use wp_logout and wp_login actions to end sessions.

We ensure sessions are cleared whenever a user logs in or out by linking these actions to an end_session function:

add_action(‘wp_logout’,’end_session’);
add_action(‘wp_login’,’end_session’);

2. Define the end_session function.

This function destroys the active session, ensuring no residual session data lingers after user transitions:

function end_session() {
session_destroy ();
}

Manually Ending Sessions in WordPress

If you need to end a session manually at any point in your theme, you can create a custom action using do_action(). Here are the steps:

1. In the functions.php file, add the following:

add_action(‘end_session_action’, ‘end_session’);

2. Call do_action whenever you want to trigger session termination.

do_action(‘end_session_action’);

If done correctly, your functions.php file should now look like this at the top:

add_action(‘init’, ‘start_session’, 1);

function start_session() {
if(!session_id()) {
session_start();
}
}

add_action(‘wp_logout’,’end_session’);
add_action(‘wp_login’,’end_session’);
add_action(‘end_session_action’,’end_session’);

function end_session() {
session_destroy ();
}

Storing and Retrieving Data in PHP Sessions

Now that your session is active, you can add data to the global $_SESSION variable, which behaves like an associative array.

Storing Data in a Session

Before saving data to a session, always sanitize it to prevent security vulnerabilities:

$foo = ‘Foo Data’;

$_SESSION[‘foo’] = sanitize_text_field($foo);

Retrieving Session Data

Once stored, data can be accessed at any time during the session:

echo $_SESSION[‘foo’];

Clearing PHP Sessions

There are times when you’ll want to clear session data without completely destroying the session. Here’s how:

Removing a Specific Session Variable

To clear an individual session variable, use unset(), which removes the specified key from the session array:

unset($_SESSION[‘foo’]);

Clearing All Session Variables

To remove all session data but keep the session itself active, use session_unset(), which is functionally identical to setting $_SESSION to an empty array:

session_unset();

// or

$_SESSION = [];

Something to Consider When Using PHP Sessions in WordPress

While PHP sessions can be incredibly useful, if you are building a scalable or load-balanced website, you may not want to use sessions. HTTP is Stateless, and PHP SESSIONS are State-driven. 

Other things to consider for WordPress environments:

  • Server-Side Storage: Sessions are stored on the server, and routing each session to the proper server requires a more complex configuration, creating a single point of failure for the users whose sessions are stored on that server. If using PHP sessions, ensure that your hosting provider supports session persistence.
  • Page Caching Conflicts: Many WordPress caching plugins do not account for session-based data, which can lead to inconsistent behavior. If you use a caching plugin, configure it to exclude pages that rely on sessions.
  • Performance Considerations: While PHP sessions aren’t typically resource-intensive, excessive use can increase server load. When possible, consider alternative solutions like storing session data in cookies or using WordPress transients.

When possible, it is best to store session information in the client’s browser. Though it may not be extremely expensive for the server resources to query session objects, it is always wise to reduce overhead whenever possible.

By correctly implementing PHP sessions in WordPress, you can maintain efficient session management while avoiding the common pitfalls. Looking for reliable website maintenance and hosting to keep your WordPress site running smoothly? Our team is here to help. Contact us today to learn more about our comprehensive support services.

Let’s Talk Hosting & Maintenance

Comments

There are currently 17 responses.

Les F
April 12, 2021

This may have worked in the past but from what I heard, WordPress changed and won’t let you start a session anymore. Please correct me if I am wrong. I had to just session_start(); and it works fine but it doesn’t start for me if I use add_action(‘init’….. Also, by running session_start() , the site health complains loudly, it says…

A PHP session was created by a session_start() function call. This interferes with REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.

Also it causes a failure with REST API as it predicted above and gives this error.

The REST API is one way WordPress, and other applications, communicate with the server. One example is the block editor screen, which relies on this to display, and save, your posts and pages.

The REST API request failed due to an error.
Error: cURL error 28: Operation timed out after 10002 milliseconds with 0 bytes received (http_request_failed)

I must have session for the plugin I am building and I am going bald pulling my hair out over this issue.

Reply
    Nathan
    June 1, 2021

    Les F.

    I just found some time to test this on a brand new WP installation and I am not running into the same issue you are seeing. The code is still working as expected on my end.

    Reply
Glenn
March 27, 2021

I use Sessions in one of the plugins I built for a client. I recently began getting this message in “Site Health Status”: “A PHP session was created by a session_start() function call. This interferes with REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.” In doing some more digging, it appears WordPress began integrating its REST API in Version 4.7 and had also integrated it into wp-admin by version 4.8.0. As far as I can tell from other reading, the REST API will not work with an open PHP Session — which seems to imply that the use of PHP sessions in WordPress is probably a thing of the past. Have I got this right?

At present cookies seem to be the only viable alternative. Is that your take?

Reply
Jamie Costello
August 18, 2020

Hi Nathan,

Sessions can be quite trick for beginners to understand so thank you for putting this together and helping educate poeple.

Great site you have here too!
Take care
Jamie

Reply
Giovanni
April 11, 2019

Nice tutorial. Thank you!

Reply
Mike Polek
February 25, 2019

Please note that some of the add_action statements above have “smart quotes” (left single quote and right single quote). PHP won’t parse them correctly if people attempt to copy the code. Please ensure that proper single quotes are used so that if the code is pasted into a text document, it will parse correctly.

I believe the ‘init’ add_action is OK. The other three add_action statements seem to have left and right quotes.

Reply
Mike Polek
February 25, 2019

Where you show the function start_session() the second time, the second right brace is missing. This will cause web sites not to function if any attempts to copy/paste the code.

Reply
    Nathan Friend
    February 25, 2019

    You are correct. Thanks for letting us know. I have updated the posts and corrected it.

    Reply
Andrei
June 14, 2018

Thanks for the article. What I don’t quite get though is the session ending part. A session is meant to end when a user logs in?

So if user 1 logs in and doesn’t log out, user 1 session will end when user 2 logs in? How will that work in a private site where each visitor is a user?

Reply
Marco
November 7, 2017

Hello, nice tutorial explained very clearly, however, this procedure only works using the functions, whereas using OOP programming generates an error.

In particular I did a kind thing like:

class MyClass
{
public function __construct()
{
add_action( ‘init’, array( $this, ‘session_start’ ), 1 );
}

public function session_start()
{
if ( ! session_id() )
session_start();
}
}

but i get this error:

Warning
: call_user_func_array() expects parameter 1 to be a valid callback, function ‘megamall_compare_setup_plugin’ not found or invalid function name in
C:my_serverwp-includesclass-wp-hook.php
on line
298

Reply
Fabiano
August 24, 2017

Thank you!

Reply
Paul Swarthout
August 10, 2017

This looks like it will work well. I’m converting an extensive Classic ASP website to a WordPress site and writing plugins to handle the admin functionality within the website. You mention in the last paragraph: “When possible, it is best to store session information in the client’s browser”….are you referring to the setCookie(cookie,cookieValue) call and $_COOKIE[‘cookie’] or to some other mechanism to make that happen?

Reply
sanyam singhal
October 4, 2016

It worked Great

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

4 × four =

Request A Quote

Let's take your business to the next level. Fill out the form below to get started!

"*" indicates required fields

Name*
Sign me up for IronMail
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
This field is for validation purposes and should be left unchanged.