How to read wordpress cookies in my website?

I want to integrate my website with wordpress.I want to know as to how can i read wordpress cookies so that i dont need to authenticate users again in my website.I tried including the header file of wordpress in my website, but then i was unable to connect to the database of my website.Both of which are different.Can i set additional parameters of cookies like user level,etc?My website is written in php.

Related posts

Leave a Reply

2 comments

  1. 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)

  2. 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