Page 1 of 1

Set Javascript Cookie, Access it With PHP

Posted: Tue Aug 17, 2010 10:43 am
by Felix K Ssekamwa
<script language="JavaScript">
document.cookie = "scrwidth="+screen.availWidth;
</script>
<?php
echo $_COOKIE["scrwidth"];
?>


The first time i go to this page, it successfully sets the java cookie but doesn't echo the cookie contents with the following PHP code. I have to refresh the page for it to be echoed by PHP. What i want is to echo it the first time i get to this page without the need for refreshing. Any help, pliz!

Re: Set Javascript Cookie, Access it With PHP

Posted: Tue Aug 17, 2010 11:58 am
by shawngoldw
I think $_COOKIE gets populated when the page loads. This means that using $_COOKIE[] you can only access the values that were set when the page was requested, not the changes you make during the execution of the page.

Shawn

Re: Set Javascript Cookie, Access it With PHP

Posted: Tue Aug 17, 2010 3:12 pm
by PHPHorizons
shawngoldw is exactly right. But it's even worse than that! Your php code executes on the server. The javascript executes on the client's computer. Therefore, you PHP code attempting to access the cookie is executed ages before the javascript code is executed. What shawngoldw says applies to cookies set using PHP, and then accessed using PHP.

Cheers

Re: Set Javascript Cookie, Access it With PHP

Posted: Tue Aug 17, 2010 3:28 pm
by shawngoldw
That is very true too.
And you can call me Shawn :)

Re: Set Javascript Cookie, Access it With PHP

Posted: Tue Aug 17, 2010 7:44 pm
by PHPHorizons
That's what's up Shawn ;) Cheers

Re: Set Javascript Cookie, Access it With PHP

Posted: Wed Aug 18, 2010 2:54 am
by Felix K Ssekamwa
Hey Shawn and Horizons, thanx nuff. It's one thing i had totally overseen. Nuff RASpect.