1

Can I access a cookie written with jQuery's cookie plug-in with PHP? I know you can't set Javascript equal to PHP or vice versa, but IN ESSENCE is:

$.cookie('var') = $_COOKIE['var']?

Again, I know you can't set them equal to each other, but if I set it in jQuery and then go to another page, can PHP access it? I've read lots of posts about this, but I can't seem to find an answer to this part.

Note, if I look in Firefox's preferences, I can see the cookies are there, so I know they're set.

1
  • Yes, they're the same. PHP can handle cookies set by JS and vice versa. Commented Jan 14, 2011 at 20:52

2 Answers 2

1

Yes.

But... Klaus Hartl's jQuery cookie plugin (I'm assuming this is the one you are using) defaults to setting the cookie's path to that of the current document. If the PHP file you were trying to echo from was in a different folder, the cookie wouldn't have been sent.

You can set the cookie's path when you set the cookie:

$.cookie('name', val, { path: '/' });
Sign up to request clarification or add additional context in comments.

5 Comments

Then why do I get an undefined index error on the next page when I try to echo them?
Debug your page's cookies in browser using native tools or some extensions (like Firebug + Firecookie). Check if the cookie was really set in JS. Dump PHP's $_COOKIE array to check all received cookies.
I did print_r on the $_COOKIE and the only thing that is there is the CodeIgniter session. Could CI be erasing them? I check Firefox's preferences and they're still there but I can't echo them.
«I check Firefox's preferences and they're still there but I can't echo them» — check cookies path. It's important. Try to set cookie with josh3736's code: $.cookie('name', val, { path: '/' });
@shummel7845: Glad I guessed correctly. Also, keep in mind that the plugin defaults to expiring the cookie at the end of the session (when the browser closes). Add expires: 365 (days) to persist the cookie.
0

The cookies you have in PHP is the same that you have in JavaScript. They are equal. Cookies have some options to set acceess scope, lifetime and so on. If you'll set a cookie for all the domain, it will be seen in PHP.

2 Comments

Could CodeIgniter (which is what I'm using) be erasing them? I am loading a login page immediately after setting them.
I don't know if it could. See josh3736's comment first. Seems it's your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.