Set Javascript Cookie, Access it With PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Felix K Ssekamwa
Forum Newbie
Posts: 2
Joined: Tue Aug 17, 2010 10:17 am

Set Javascript Cookie, Access it With PHP

Post 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!
shawngoldw
Forum Contributor
Posts: 212
Joined: Mon Apr 05, 2010 3:38 pm

Re: Set Javascript Cookie, Access it With PHP

Post 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
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: Set Javascript Cookie, Access it With PHP

Post 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
shawngoldw
Forum Contributor
Posts: 212
Joined: Mon Apr 05, 2010 3:38 pm

Re: Set Javascript Cookie, Access it With PHP

Post by shawngoldw »

That is very true too.
And you can call me Shawn :)
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: Set Javascript Cookie, Access it With PHP

Post by PHPHorizons »

That's what's up Shawn ;) Cheers
Felix K Ssekamwa
Forum Newbie
Posts: 2
Joined: Tue Aug 17, 2010 10:17 am

Re: Set Javascript Cookie, Access it With PHP

Post by Felix K Ssekamwa »

Hey Shawn and Horizons, thanx nuff. It's one thing i had totally overseen. Nuff RASpect.
Post Reply