user319854
user319854

Reputation: 4106

php and javascript cookie

why php get cookie new value only when i refresh page twice. When run page first time, php do not get cookie value.

Thanks

<script type="text/javascript"> 
var name = 'test1';
var value = '1234';
var expirydays = '1';
expiry = new Date();
expiry.setDate(expiry.getDate() + expirydays);
document.cookie = name+"="+escape(value)+";expires="+expiry.toGMTString();
</script>

<?php       
print_r($_COOKIE);
?> 

Upvotes: 0

Views: 854

Answers (2)

Pekka
Pekka

Reputation: 449395

You are confusing how PHP and JavaScript work.

PHP is run first, on server side.

JavaScript is run long after PHP has run, on client side in the user's browser.

A cookie you set in JavaScript will never be visible to the PHP script that generated the Javascript: It is too late. You will have to reload the page.

Incidentally however, even values set through PHP's own setcookie() will be visible only after a page reload, because the $_COOKIE variable is populated when the script starts.

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227220

PHP is run on the server, and JavaScript on the client. The PHP code is run before the JavaScript code is run, so the 1st time, PHP doesn't have the cookie yet. It works the 2nd time, because the cookie is already there.

Upvotes: 0

Related Questions