Boardy
Boardy

Reputation: 36205

Read a PHP cookie from JavaScript

I have a PHP script which sets a cookie called user. I need to be able to read the value from this cookie in javascript.

Can this even be done.

Thanks for any help you can provide.

Upvotes: 11

Views: 42482

Answers (7)

Paul Leclerc
Paul Leclerc

Reputation: 1137

In Drupal application which use the Cookie Symfony library, you need to set specific cookie parameters in order to access it in javascript.

Using js-cookie library which is on the drupal core, cookies.get() won't display the php Cookies that would have been set as HttpOnly.

You can get you cookies parameters in Application > Cookies in Chrome for example.

Upvotes: 0

Marc B
Marc B

Reputation: 360702

There's no such thing as a "PHP cookie" or a "javascript cookie". There's just cookies, which you can access from PHP and Javascript. In JS, you'd use document.cookie to access the raw cookie data. There's plenty of libraries which give you finer-grained access as well,

Upvotes: 16

webworker
webworker

Reputation: 21

I tested it. You can read cookie which created with php.

You only need to add '/' (path)!!

setcookie("username", $username, $expire, '/');

Upvotes: 2

Brad
Brad

Reputation: 163262

Take a look at document.cookie.

Example from http://www.quirksmode.org/js/cookies.html

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toUTCString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

Alternatively, if you use jQuery, there is a nice plugin: http://plugins.jquery.com/project/Cookie

Upvotes: 4

Patrick Moore
Patrick Moore

Reputation: 13344

Whether the cookie originates in JS or PHP should not matter. The cookie is stored for the domain, with a name and value. It does not contain information relating to how it originated.

Here is a plugin for accessing cookies in jQuery: http://plugins.jquery.com/project/Cookie

Upvotes: 1

yasar
yasar

Reputation: 13748

You can access your cookies with document.cookie Check this link: http://www.w3schools.com/js/js_cookies.asp

Upvotes: 5

rogerlsmith
rogerlsmith

Reputation: 6786

Since PHP is a server side script and JavaScript runs in the browser, you'll need to send the cookie to the browser in a hidden form variable, or use an AJAX call from JavaScript to get it from the server.

Upvotes: -8

Related Questions