note 104198 added to function.setcookie
| From: | chris at styl dot ee | Date: | Tue, 31 May 2011 15:10:29 +0000 |
| Subject: | note 104198 added to function.setcookie | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-180124@lists.php.net to get a copy of this message | ||
I was searching for a simple example of creating a cookie, storing a random number and updating it
on refresh. I couldn't find one so I had to figure it out on my own....
- - - -
One thing to *NOTE* is technically you can't update a cookie, you can only overwrite it with a
new one with the same name.
- - - -
This creates a random number, stores it in a cookie, then references it on refresh, checks for
duplicates and does necessary correction, then stores it again, rinse and repeat...
<?php
ob_start();
$MaxCount = 4;// set the max of the counter, in my tests "4" = (0,1,2,3) I adjusted below
(+1) to get a "real" 4 (0,1,2,3,4) this is in reality 5 keys to humans, you can adjust
script to eliminate "0", but my script makes use of the "0"
$random =(rand()%($MaxCount+1));//give me a random number limited by the max, adding "1"
because computers start counting at "0"
if(!isset($_COOKIE['random'])){// check if random number cookie is not set
//echo"not set";
setcookie('random', $random);//set the cookie for the first time
}else{
$lastRandom= $_COOKIE['random']; //hold the last number if it was set before
if($lastRandom == $random){//some logic to avoid repeats
if($random < $MaxCount){//if below max, add 1
$random++;
//echo "under the max, adding 1, ";
}elseif($random >= ($MaxCount-1)){// if for some reason the random number is more than max or
equal to it -1, and an additional -1 for max count in initial var (so in reality this -1 from intial
max var, and -1 from $random which should be the same number)
$random--;
//echo "hit the max, subtracting 1, ";
}else{
$random++;
//echo "no case match, adding 1, ";
}
//echo "(".$lastRandom.", ".$random. "), they matched initally - was it
fixed?";
}else{
//echo "(".$lastRandom.", ".$random. "), they DO NOT match";
setcookie('random', $random);
}
//echo"is set: {$_COOKIE['random']}";
}
ob_end_flush();
?>
----
Server IP: 64.71.164.2
Probable Submitter: 66.192.34.67
----
Manual Page -- http://www.php.net/manual/en/function.setcookie.php
Edit -- https://master.php.net/note/edit/104198
Del: integrated -- https://master.php.net/note/delete/104198/integrated
Del: useless -- https://master.php.net/note/delete/104198/useless
Del: bad code -- https://master.php.net/note/delete/104198/bad+code
Del: spam -- https://master.php.net/note/delete/104198/spam
Del: non-english -- https://master.php.net/note/delete/104198/non-english
Del: in docs -- https://master.php.net/note/delete/104198/in+docs
Del: other reasons-- https://master.php.net/note/delete/104198
Reject -- https://master.php.net/note/reject/104198
Search -- https://master.php.net/manage/user-notes.php