简体   繁体   中英

How to read wordpress cookies in my website?

我想将我的网站与wordpress集成。我想知道如何阅读wordpress cookies,以便我不需要在我的网站再次验证用户。我尝试在我的网站中包含wordpress的头文件,但后来我是无法连接到我的网站的数据库。其中两个是不同的。我可以设置其他参数的cookie,如用户级别等?我的网站是用PHP编写的。

In your website, include that code at the top of each files :

<?php 
define('WP_USE_THEMES', false);
require('./blog/wp-blog-header.php');
?>

...assuming your blog is in ./blog/ .

It includes the whole wordpress stack. You will have access to all wordpress functions in your code. With that you can easily check if user is logged in, roles and capabilities, but also retrieve posts or so.

Then in you code, to check user :

if (is_user_logged_in()) { ... } 

Codex : is_user_logged_in()

You can also include a logout link :

<a href="<?php bloginfo("url"); ?>/wp-login.php?action=logout/">Logout</a>

If your blog and your site are not on the same domain or subdomain, you have to customize cookie domain in wp-config.php

define('COOKIE_DOMAIN', '.domain.com'); // Share cookie on all subdomains

EDIT

If you really just want to read the wordpress cookies (which is a good choice for performance) : the cookie name is stored in a constant AUTH_COOKIE.

AUTH_COOKIE is defined in /wp-includes/default-constants.php -> line 171 as

"wordpress_" + md5( get_site_option(siteurl) )

You have to retrieve or recompute AUTH_COOKIE then read $_COOKIE[AUTH_COOKIE].

To parse it, look at wp_parse_auth_cookie() in wp-includes/pluggable.php @line 585 (indeed the format is simple user|expiration|hmac so split the chain by | and get the first element)

To make cookies work in Wordpress you need to set it special way like so in functions.php

function set_newuser_cookie() {
    if (!isset($_COOKIE['sitename_newvisitor'])) {
        setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);
    }
}
add_action( 'init', 'set_newuser_cookie');

So the important point is setcookie('sitename_newvisitor', 1, time()+1209600, COOKIEPATH, COOKIE_DOMAIN, false);

To get it

if (isset($_COOKIE['sitename_newvisitor'])) {
     echo 'Welcome back!';
}
else {
     echo 'Hello new visitor!';
}

Note : You can change cookie name 'sitename_newvisitor', value, timeout, COOKIEPATH and COOKIE_DOMAIN to fit your needs

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