PHP Session Variable to WordPress Error

I have been trying to figure out how to add session variables to WordPress Custom Pages for the past few days but have still been unable to find a solution. From researching it seems WordPress does not allow you to move Session variables from one page to the next. I have tried removing all of the 'session_start();' from each page and adding the below to functions.php file.

add_action('init', 'myStartSession', 1);
function myStartSession() {
if(!session_id()) {
    session_start();
}
}

Have also tried adding code below to the wp-config.php but to no avail.

if (!session_id())
session_start();

The session will create a unique id for each user which will be checked on the next page to see if it equals the previous id. The first page code is as follows:

$_SESSION['t'] = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1');
session_write_close();

The next page is:

$testValue = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1');
if ($testValue == $_SESSION['t'])
{$passFlag = 1;}
else
{$passFlag = 0;}
session_regenerate_id();

'session_write_close();' is called further down on this page. Any help would be greatly appreciated and if you need any further information please don't hesitate to message. Thanks.

Topic session php Wordpress

Category Web


(Making @Tom's comment into a proper answer)

PHP sessions are legacy from the beginning days of PHP when the use of DBs was rare, complex and expensive. Since then everybody moved on, and now there is nothing that a session can do that a DB will not do in a more consistent and reliable way. If you feel like you need some information stored on the server just write to the DB, whether it is to a user's meta or a new table (if your users do not map into WP users).

And since sessions require cookies in any case, you might as well just store your unique key in a cookie.


You need to add your code to the functions.php file of your theme. (Actually, adding it to your Child Theme is best, since you don't want a theme update changing things. Unless you are writing your own theme.)

So this in your functions.php file:

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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.