Created
July 12, 2017 18:16
-
-
Save datamafia/94876620ee170820cf296ca15d899257 to your computer and use it in GitHub Desktop.
PHP prototype addressing https://stackoverflow.com/questions/45038265/retrieve-user-id-from-wordpress-to-aanother-php-site/45044122
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// Session may not be started on this script, if not init session | |
if (!session_id()) { | |
session_start(); | |
} | |
// double check, once for the key, again that the result is an int larger than 0 (as WP will follow the AI rule in the DB) | |
if (array_key_exists('some_custom_var', $_SESSION) and $_SESSION['some_custom_var'] > 0){ | |
echo 'User is valid with id:'.$_SESSION['some_custom_var']; | |
}else{ | |
echo 'User is NOT valid'; | |
} | |
echo '<pre>'; | |
var_dump($_SESSION); | |
echo '</pre>'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
// in the theme's functions.php file | |
// Session may not be started on this script, if not init session | |
if (!session_id()) { | |
session_start(); | |
} | |
// explicitly label as false anytime not set (not logged in) | |
// not doing this can cause leaks or bad evals | |
if (!array_key_exists('some_custom_var', $_SESSION)){ | |
$_SESSION['some_custom_var'] = false; | |
} | |
// pulled from/original code/info here: https://codex.wordpress.org/Plugin_API/Action_Reference/wp_authenticate | |
// hooking into the "when user is wuthenticated" part of WP to set our own easy to use session var | |
function check_custom_authentication ( $username ) { | |
global $wpdb; | |
if ( ! username_exists( $username ) ) { // on fail | |
return; | |
} | |
$userinfo = get_user_by( 'login', $username ); | |
// set the session | |
//$_SESSION['some_custom_var'] = $userinfo; // this will add all the user info to the session if you need more info | |
$_SESSION['some_custom_var'] = $userinfo->data->ID; // sets the user ID to the session | |
} | |
add_action( 'wp_authenticate' , 'check_custom_authentication' ); // activates the hook | |
function clear_custom_authentication() { | |
// on logout set the custom var to false so it does not leak/persist unwanted. | |
$_SESSION['some_custom_var'] = false; | |
} | |
add_action('wp_logout', 'clear_custom_authentication'); // activates the hook |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment