Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check wordpress_logged_in cookie

there is a way to check wordpress cookie wordpress_logged_in using jquery?

I'm using cloudflare full caching, so there is no way to check if user is logged or not than this cookie, I tried to read it using jquery but seems protected and not visible, I can access it only using PHP.

Here is how I can read it right now :

$logged_in = 'no'; 
if (count($_COOKIE)) {
    foreach ($_COOKIE as $key => $val) {
        if (preg_match("/wordpress_logged_in/i", $key)) {
            $logged_in = 'yes';
        }       
    }
}

Maybe there is a possiblity to check it simply by jquery, but I didn't find how.

Thanks for helping

like image 437
Zeta Avatar asked Jan 29 '18 23:01

Zeta


1 Answers

You can't access to wordpress cookies named wordpress_logged_in using js/jquery just because it's flagged as HttpOnly:

A secure cookie is only sent to the server with a encrypted request over the HTTPS protocol... To prevent cross-site scripting (XSS) attacks, HttpOnly cookies are inaccessible to JavaScript's Document.cookie API; they are only sent to the server.

But since 3.0 wordpress add one more cookie named wp-settings-{time}-[UID] when user log in:

WordPress also sets a few wp-settings-{time}-[UID] cookies. The number on the end is your individual user ID from the users database table. This is used to customize your view of admin interface, and possibly also the main site interface.

And you can get this cookie using js/jquery. So, you can even get user ID from cookies.

Here is working js function for getting cookies and checking, if user is logged in:

function getLoggedInCookie() {
    var cookie = document.cookie.indexOf('wp-settings-time') !== -1;

    if(cookie){
        alert('Logged in');
    }else{
        alert('Not User');
    }
}
getLoggedInCookie();

jQuery solution will be to include Cookie plugin to your wordpress theme/plugin and try to use it( may need in some modifications ).

NOTE:

Provided code will work with login forms, which use standart WordPress functions and endpoints, such as http://{website-name}/wp-admin/ or http://{website-name}/wp-login.php. Third party plugins could not set cookies named wp-settings-{time}-[UID].

like image 52
Samvel Aleqsanyan Avatar answered Nov 25 '22 02:11

Samvel Aleqsanyan