703.829.0809

Using PHP Sessions in WordPress

Using-PHP-sessions-in-wordpressStarting A PHP Session

PHP sessions are a great way to track and store information specific to a user’s session within a PHP application. In this article, I will show you how to use PHP sessions in a WordPress theme. In a standard PHP application, a session would be started using the session_start function at the very top of the PHP script. This may tempt you to open the header.php file in your WordPress theme and add something like the following to begin using sessions.

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

Though this would work, it is not the most efficient way to start a session in WordPress. WordPress provides an Actions Api that we are able to attach custom functions to. That is the method we will be using in this example. We are going to add all the following code to the very top of our themes functions.php file.

1: We will use the init action provided by WordPress to handle starting a PHP session. First, we add the action that will call a function called start_session like this when WordPress first initiates.

add_action('init', 'start_session', 1);

2: Second we will create the start_session function. Notice the function is first checking to see if a session is already active before setting a new one using a function called session_id.

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

Ending A PHP Session

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 also provides a few ways for us to do just that in the Actions Api.

1: In WordPress we are going to need to clear out the session once a user has logged out or a new user has logged into the website. We will use two provided actions, wp_logout and wp_login, to call a function we will create called end_session();

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

2: Second we will create the end_session function like this:

function end_session() {
session_destroy ();
}

Forcing A Session To End

We can use a custom hook to end a session anywhere within the theme by using the do_action function provided by WordPress to call the end_session function we created above.

1: In the functions.php file we would add the following.

add_action('end_session_action', 'end_session');

2: Add the following anywhere in the application you want to end the session.

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 ();
}

You can now add data to the global $_SESSION variable that will be accessible at any point within the application during a user session by accessing the $_SESSION variable. The variable is an array; below is an example of adding data to the session array.

$foo = ‘Foo Data’;
$_SESSION[‘foo’] = $foo;

Something to think about: 

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. Sessions are stored and handled by the server. Routing each session to the proper server requires more complex configuration and creates a single point of failure for the users who’s sessions are stored on that server. When possible, it is best to store session information in the client’s browser. Though it may not be extremely expensive to the server resources to query session objects, it is always wise to reduce overhead whenever possible.

Thank you for reading. I hope you find this article helpful and please comment below with any questions. Happy coding! 🙂


Related Posts


Comments

There are currenty 7 responses.

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_server\wp-includes\class-wp-hook.php
on line
298

Reply
    Nathan D Friend
    November 13, 2017

    The error message you shared doesn’t look to be related. It is referring to a plugin function missing “megamall_compare_setup_plugin”.

    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
    Nathan Friend
    August 25, 2017

    Yes, the setCookie(cookie, cookieValue) method is what I a referring to in that last paragraph. Thanks!

    Reply
sanyam singhal
October 4, 2016

It worked Great

Reply
    Nathan D Friend
    November 13, 2017

    Sanyam,

    Glad to hear it worked for you, would you mind sharing how you used it in your project?

    Reply

Leave a Reply

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

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