Can't read from cookie until second load?

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
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Can't read from cookie until second load?

Post by JAB Creations »

I'm using GET to set cookies such as index.php?audio=1&bandwidth=2. The header file sets a cookie per each GET in the url. However the page does not read the cookie initially and requires a reload to correctly display the cookie's value.

My files are as so...
1.) header.php

2.) header-cookies.php (included at bottom of header.php and used to process GET in url)

3.) index.php (this loads last and is the page initially requested)

An example of setting a cookie for index.php?audio=1 would be...

Code: Select all

if ($_GET['audio'] == "0") {setcookie('audio','0',time()+2592000,'/');}
else if ($_GET['audio'] == "1") {setcookie('audio','1',time()+2592000,'/');}
What am I be doing wrong?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

You aren't doing anything wrong, that's how cookies work.
User avatar
JAB Creations
DevNet Resident
Posts: 2341
Joined: Thu Jan 13, 2005 6:44 pm
Location: Sarasota Florida
Contact:

Post by JAB Creations »

Perhaps I should detect if a GET is in the URL first and if not then go by the cookie?
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

You should probably be using sessions in this case for each page request, and set a cookie to remember their last request if they end up closing the browser. I could be off, as I have no idea what your trying to accomplish.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

PHP Docs wrote:Cookies will not become visible until the next loading of a page that the cookie should be visible for.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

I never knew that. :-p
Another reason I like sessions.

Sessions 1, Cookies 0. :-D
Post Reply