setcookie problem

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
btd
Forum Newbie
Posts: 5
Joined: Thu Nov 13, 2008 12:32 pm

setcookie problem

Post by btd »

I've been looking at this code for the last 2 days and just can not figure out the mistake.
The test consist of 2 files trying to set and read the same cookie.
file1:
<?php

$hour = time() + 3600;
setcookie( 'ID_FT1', "me2", $hour);
$xtmp_ck = $_COOKIE['ID_FT1'];
echo nl2br("\n x022 name: $xtmp_ck \n");

?>

file2:
<?php

$hour = time() + 3600;
setcookie( 'ID_FT1', "me3", $hour);
$xtmp_ck = $_COOKIE['ID_FT1'];
echo nl2br("\n x023 name: $xtmp_ck \n");

?>
these files allready exist at followtrader.com/test2.php and test3.php.

output of displaying test2 the 1st time is:
x022 name:

the 2nd time:
x022 name: me2

If you display test3, then sometimes you will see inconsistent results too.

Any ideas would be appreciated.

BeattheDart group.
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Re: setcookie problem

Post by shiznatix »

as the manual states, the cookie will not be active until the next page load because php gets the cookies from the clients browser as soon as the page is requested so if you set the cookie the same page load that cookie will not yet be available because the bowser did not receive the cookie because you just set it and the page has not reloaded yet.

kas sa said aru?
btd
Forum Newbie
Posts: 5
Joined: Thu Nov 13, 2008 12:32 pm

Re: setcookie problem

Post by btd »

Thanks a lot for your reply and help.
very usefull - obviously.

I relied on w3schools.com for the manual.
I just realized that I am missing a big picture.
I thought that $_COOKIE is a array of global variables on a browser's machine, and treated it as such.
Now, I am not really sure how it all works.
What is communicated over the tcp/ip using a protocol?
I am pretty sure that "setcookie()" can be traced using network analizer.

I know that cookies reside on a local computer.
where is the php code parsed? ON the server side or not?
I am assuming that it is only parsed and converted to html only once.

Can somebody point me in the right direction for a sucsinct summary?
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: setcookie problem

Post by Eran »

PHP is parsed on the server. Since the environment information available to your script depends on the headers sent to it by the browser before it starts parsing, any cookie created in the current script will not be available until the next request from the same browser.
Post Reply