PDA

View Full Version : PHP is not reading cookies until i refresh - help



sic
20 May 2009, 05:45 PM
I am having the following problem. On a php script I am setting a cookie with javascript and a few lines lower I am trying to recall the value in php. The php is not getting the value unless I refresh the page. Can you please help me find a solution?
My code is as follows...



<SCRIPT LANGUAGE=JavaScript>
hash = parent.location.hash;
ar=hash.substring(1);
document.cookie = name+"video="+ar;
</SCRIPT>

<?php
$ar = $_COOKIE["video"];
echo "ar-->".$ar;
?>



the reason I am doing this is because I dont know some other way to pass a variable from javascript to php (on the same script).
I want to read a variable from the url not using GET or POST but using the hash (#) value.
I am doing this because I want to change the URL from a click on a flash object without refreshing the page.

Alan
20 May 2009, 08:00 PM
Simple answer is PHP get's executed first. And no you can't change this. :)

You have basic 3 solutions:

Set the cookie with PHP and read it with PHP.
Set the cookie with JS and read it with JS.
Set the cookie with PHP and read it with JS.


Note that if setting the cookie using PHP, you cannot output anything before it. Otherwise you will get a "header's already sent" error.

PHP.net - setcookie (http://ie2.php.net/manual/en/function.setcookie.php)

Just to add another 2 cents, if you want to delete a cookie, set the cookie to an expiry time that has already occured.