wp_get_session_token()WP 4.0.0

Gets the current session token of the current user from the cookie logged_in.

Works only for authenticated users. If the user is not authenticated, the function will return '' an empty string.

Use Cases

  1. Session Uniqueness Check: Can be used to track active user sessions and prevent duplicate logins.

  2. Security: Checking the session token helps enhance protection against hacking attempts or session hijacking.

This method is often used in conjunction with other session management functions:

No Hooks.

Returns

String. Token. Or an empty string.

Usage

wp_get_session_token();

Examples

0

#1 Demo of what the function outputs

var_dump( wp_get_session_token() );
// string(43) "6nhBEF74hfMqVO1p0sdlJQ78Ui5yq85EZO8JIj31"
0

#2 Example: Session Uniqueness Check

In this example, all active sessions for the current user are checked. If a session with a token different from the current one is found, all other sessions are terminated.

if ( is_user_logged_in() ) {
	$current_token = wp_get_session_token();
	$all_sessions = wp_get_all_sessions( get_current_user_id() );

	foreach ( $all_sessions as $token => $session_data ) {
		// If another session is found, terminate it
		if ( $token !== $current_token ) {
			wp_destroy_other_sessions();
			break;
		}
	}
}

Changelog

Since 4.0.0 Introduced.

wp_get_session_token() code WP 6.9.1

function wp_get_session_token() {
	$cookie = wp_parse_auth_cookie( '', 'logged_in' );
	return ! empty( $cookie['token'] ) ? $cookie['token'] : '';
}