Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cookie Counter Problem

Status
Not open for further replies.

codeWarrior456

Technical User
Oct 27, 2002
27
0
0
US
I am trying to use a cookie based counter on my website to keep my counter value from increasing if the user hits the refresh button. However, my setcookie function is not working properly and I can't figure out why. What I have determined is that it will work outside of my if block, but not inside it. The page is going inside the if block since my confirmation message is printing. Can anyone help me figure out why my cookie isn't being sent.

Thanks in advance.

Part of my code:

if(!isset($_COOKIE[cookietest]))
{
//set cookie
setcookie("cookietest", $_SERVER["REMOTE_ADDR"], time()+360);
print "Hello World";
}
 
be carefull with the issues of the setcookie function... from php.net:

Common Pitfalls:

1. Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
 
Check this out:
Code:
if(!isset($_COOKIE['cookietest']))
{ 
//set cookie
setcookie("cookietest", $_SERVER['REMOTE_ADDR'], time()+360);
//increase the counter value
print "Hello World";
}

I have some experience with using cookies and I suggest you not to use them. They aren't working properly everywhere. I faced some cases when even in browser with cookies turned on, the cookie wasn't sent along with the http request. Better way is to store IP's in the database and compare them with the $_SERVER['REMOTE_ADDR'] at the beginning of the code. (what you try to do - store IP address in cookie - has no sense ;-))
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top