Spoofy
Spoofy

Reputation: 651

Get/Read Javascript cookie with PHP

I have a theoretical question..

I know that you can get/read a PHP cookie with javascript by using: document.cookie

Is there a similar way to do this in PHP?

Can PHP get/read a cookie that is created i JavaScript? If yes, then how can you do that?

Upvotes: 16

Views: 43138

Answers (5)

chokey2nv
chokey2nv

Reputation: 11

Javascript can set cookies in two ways (of i know) window.cookie and document.cookie. if use window.cookie php cannot assess the cookie, php can only assess cookie set by document.cookie.

javascript

document.cookie = 'name=value';

PHP

print_r($_COOKIE);

you will see your javascript created cookie inside, among other created by php.

or

echo $_COOKIE['name'];

Assess php cookie with javascript use same document.cookie to assess document (php) cookies and javascript cookies created with document.cookie.

Javascript only can assess window.cookies created cookies

Upvotes: 1

StackSlave
StackSlave

Reputation: 10627

To see them you can do this:

foreach($_COOKIE as $v){
  echo htmlentities($v, 3, 'UTF-8').'<br />';
}

For a single cookie it's just:

echo htmlentities($_COOKIE['cookieName'], 3, 'UTF-8');

Feel free to change the quote style (3 being ENT_QUOTES) and charset to suit your needs.

Note: The cookie has to have been set on the same domain for you to access it.

Upvotes: 1

Justin Domnitz
Justin Domnitz

Reputation: 3307

PHPglue's answer is good, but has several typos in it. It also doesn't tell you what the index is which can be very helpful.

foreach($_COOKIE as $key=>$value)
{
  echo "key: ".$key.'<br />';
  echo "value: ".$value.'<br />';
};

My issue was that I was setting my cookie in Javascript with periods in the name. These were being converted to underscores. For example cookie name, facebookLogin.myapp.com was being changed to facebookLogin_myapp_com. Once I ran the code above, I was able to see that the name was different than expected and read the name from PHP correctly.

Upvotes: 1

Seyed Ali Roshan
Seyed Ali Roshan

Reputation: 1

I think this is a good way to set all intimation in one cookie and use an symbol between your information. Then use for example this in "PHP" after set cookie by JavaScript

$mystr = print_r($_COOKIE);
$way=explode(";",$mystr);

Upvotes: 0

jacobroufa
jacobroufa

Reputation: 391

You can use $_COOKIE, the superglobal. Just reference it like you would any array, where $_COOKIE['key_name'] is the cookie you want to access.

See the PHP API documentation.

Upvotes: 23

Related Questions