简体   繁体   中英

Check if WordPress password protect cookie exists

With WordPress, if you're using password protected pages, when the user uses a successful password, a cookie is generated looking something like this:

wp-postpass_299da1fd9cb967a93782c5397fa3a35e

Is there anyway in PHP to do a check if this cookie exists?

Even just check if a cookie exists which starts with wp-postpass_ ?

Contents of $_COOKIE when I run var_dump($_COOKIE) :

array(9) {
    ["wordpress_test_cookie"] => string(15)
    "WP Cookie check" 
    ["wp-postpass_299da1fd9cb967a93782c5397fa3a35e"] => string(34)
    "$P$BXtsZ0i1qom3bqiFk4b9GeG8l9dFVG." 
}
if(isset($_COOKIE)){
    foreach($_COOKIE as $key=>$val){
        if(strpos($key,'wp-postpass_') === false) {
        //not found
        }else{
        //found
        }
    }
}

I found a more elegant solution than the accepted answer on WordPress Developer Docs to see if the cookie exists:

if ( isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) ) {
     //custom code 
}

Likewise, if you want to check if the cookie doesn't exist:

if ( ! isset( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ) ) {
    //custom code
}

This code is useful for pages that might not have password protection because they are an archive page or what not, but the content it contains may be protected (such as a post).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM