0
votes

My understanding of PHP sessions is that they let us track variables from page to page on a site. But I seem to be seeing something different with WordPress. I have the hook below in my functions.php file:

add_action( 'wp', 'sa_clear_session_email' );
function sa_clear_session_email() {

    if ( ! is_page( 'Pricing ' )  )
        return;

  $ret = session_start();
  if ($ret) {
    $s_id = session_id();
    trace("M20D:Pricing page. Started session $s_id");
  }
  else {
    trace("M20E:Pricing page. Unable to start session");
  }
unset( $_SESSION['user_email'] );

So, if this is the Pricing page, the code opens a session and clears the 'user_email' variable.

Also in functions.php is

add_action( 'wp', 'woa_add_membership_auto_on_checkout' );
function woa_add_membership_auto_on_checkout() {
    if ( ! is_page( 'checkout' ) || ! is_checkout() ) {// is_checkout() returns true if viewing the checkout page
        return;
    }

 $ret = session_start();
  if ($ret) {
    $s_id = session_id();
    trace("M9F:Started session $s_id");
  }
  else {
    trace("M9F:Unable to start session");
  }
$email = $_SESSION['user_email'];

This code waits for the checkout page and then tries to use the session opened in the first code. The issue I'm having is that even though I cleared 'user_email' in the first hook function it's not cleared in the second, and the reason is that the session_id I get in the first code is not the session_id I get in the second code.

Does anyone understand what's happening here?

Thanks.

2
Usually, the init action is used to start the session. If that doesn't work, it's probably your server isn't saving sessions properly. - ub3rst4r
can you check if ( ! is_page( 'Pricing ' ) ) and if ( ! is_page( 'checkout' ) || ! is_checkout() ) { both are working properly and loop goes inside function? - Ash Patel

2 Answers

1
votes

First, do not use session_start() without checking is session started already.

Example:

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

Secondly, do not use it in "wp" hook. use it in init hook OR template_redirect hook.

Example:

add_action('init', 'yourclass');

If the problem still exists let me know but I believe you will solve your problem and stop resetting the session with these two tweeks. :)

1
votes

user854993,

I've tried both these ideas, without success. In the init hook I have

add_action('init', 'myStartSession', 1);
function myStartSession() {
    if(!session_id()) {
        session_start();
    }
    $s_id = session_id();
    trace("M00C:init hook: session_id is $s_id"  );
}

But the trace line shows that this gets executed multiple times and almost each time the session_id is different:

enter image description here

I'm ready to give up trying to use sessions with WordPress and instead store the user_email value in a user meta variable, where the user is the main superadmin (me). That should be stable, with none of these problems

What do you think?