Connecting Tech Pros Worldwide Forums | Help | Site Map

Help with cookies

Newbie
 
Join Date: Nov 2006
Posts: 23
#1: Jan 14 '08
Every time when I run my code the result is 1 time. I do not understand why? I imagine that the time should be grow. It should be 1 time, 2 time and so on.
My code is:

<?
$counter=0;
$counter++;
setcookie('counter',$counter);
if(isset($_COOKIE['counter']))
$counter1=$_COOKIE['counter'];
echo $counter1."<br>";
echo "Last visit $counter1 times";
?>

MarkoKlacar's Avatar
Expert
 
Join Date: Aug 2007
Location: Stockholm, Sweden
Posts: 294
#2: Jan 15 '08

re: Help with cookies


Quote:

Originally Posted by Eglute

Every time when I run my code the result is 1 time. I do not understand why? I imagine that the time should be grow. It should be 1 time, 2 time and so on.
My code is:

<?
$counter=0;
$counter++;
setcookie('counter',$counter);
if(isset($_COOKIE['counter']))
$counter1=$_COOKIE['counter'];
echo $counter1."<br>";
echo "Last visit $counter1 times";
?>

Hi,

Well since your $counter variable is being re-set every time the user visits the site the fact that it always displays '1' is not that strange.

What you should do is check whether the cookie is set or not before you assing $counter a value.

if(isset($_COOKIE['counter'])){
// your code for outputting the value of $counter
}
else{
// create variable $counter and setting the cookie
}

Hope you get it in order.

Cheers
Reply


Similar PHP bytes