• I have an add filter hook for wp_authenticate_user where I am setting a session var for later use in an API, if i check the var IN the function it displays as expected outside the function it is NULL

    function sbci_get_user_pass($val1, $val2){
    if(!session_id()) {
    session_start();
    }
    $_SESSION["val2"] = $val2;
    echo $_SESSION["val2"]; // displays actual value
    return $val1;
    }
    add_filter('wp_authenticate_user', 'sbci_get_user_pass',1,2);

    var_dump($_SESSION["val2"]); // displays NULL

    any suggestions or insight is appreciated.

Viewing 6 replies - 1 through 6 (of 6 total)
  • Moderator threadi

    (@threadi)

    This is because WordPress does not use PHP sessions. Therefore, the variable does not exist outside of your hook, which is executed later than the global environment.

    Tip: You would need to execute session_start(); via the init hook. You can then access a session in all hooks that run afterwards.

    See also: https://kinsta.com/blog/wordpress-cookies-php-sessions/#php-sessions

    This plugin may also help: https://wordpress.org/plugins/wp-native-php-sessions/

    Thread Starter jester48

    (@jester48)

    this is what I have, still no joy

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


    function sbci_get_user_pass($user, $password){
    if(!session_id()) {
    session_start();
    }
    $_SESSION["pwd"] = $password ;
    return $user;
    }
    add_filter('wp_authenticate_user', 'sbci_get_user_pass',1,2);
    Moderator threadi

    (@threadi)

    The output you use to test it is missing from your code. Where do you execute it?

    Hi @jester48 ,

    session_start() does not work well with WordPress.

    I think it is preferable to use the transient options specific to WordPress.

    https://developer.wordpress.org/apis/transients/

    Example:
    set_transient(htmlentities($BWvars), htmlentities($code), 900);
    // 15 minutes.

    Bye.

    Thread Starter jester48

    (@jester48)

    @threadi, I found ther issue. The 2FA feature of a plugin appears to be destroying the session, I was able to bypass this by using the transient option described by @alessandro12

    Moderator threadi

    (@threadi)

    Good find. However, I would be cautious with transients in the frontend or as long as you are not logged in. These are not stored there on a user-specific basis. This cannot be compared to a PHP session in this situation.

Viewing 6 replies - 1 through 6 (of 6 total)

You must be logged in to reply to this topic.