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?
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?
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.
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.
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.
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
HTTP is a stateless protocol. During Client Server communication to maintain state we use some techniques. Cookie is one of them. Generally we use Cookies to identify an user. When first time user send request to the server in response server sends a set of Cookies. Which browser stores in Client machine. Next time when the same user request again browser send the information store in Cookies. Through which server get to identify the user. Create, Remove or Read a PHP Cookie using Setcookie method
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);