Dionisio Barboza
Dionisio Barboza

Reputation: 15

Cookies and Random Numbers in PHP

It's a quick question:

How can I generate cookies with a random identifier ?

I mean I'm trying to set a cookie whose name comes from a rand number and then I try to read the cookie but I get errors.

$random = rand(1,1000);
setCookie($random,'value',time()+3600,"/");
echo $_COOKIE[$random]; //and I get a Undefined offset

Upvotes: 1

Views: 2956

Answers (2)

Dimas Lanjaka
Dimas Lanjaka

Reputation: 294

The valid command is setcookie NOT setCookie
 Solutions:
 <?php
$random = md5(rand(1,1000)); //encoded with md5, avoid bad string output.
/* Random Value */
setcookie("TestCookie", $random, time()+3600); 
$_COOKIE['TestCookie'] = $random;
/* Random Cookiename */
$randomcookie = $random;
setcookie($random, "value", time()+3600);
$_COOKIE[$randomcookie] = "TestCookie";
$_SESSION['randomcookie'] = $_COOKIE[$randomcookie]; //put into session for saved on cache localhost
/* Output */
echo $_COOKIE["TestCookie"]; //output your random cookievalue
echo $_SESSION["randomcookie"]; //output your random cookiename
  ?>

Upvotes: 0

travisneids
travisneids

Reputation: 613

The reason your cookie is NULL of the following (pay attention to the bolded text):

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST.

Your code sets the cookie with a name of the current generated number. You can't actually access the cookie until you reload the page/navigate to a new page.

If you are refreshing this page you are first generating a new random number and setting it to $random. Then setting a new cookie (which again can only be accessed after a page load) with the current $random, then trying to retrieve a cookie using that same $random variable which has already been updated with a new number and set on a new cookie that isn't available until a new page load =)

Does that make sense?


EDIT

I just saw you came to that conclusion on your own. To answer your question asking if cookies are saved client side or server side: client side in the browser.

If you are going to be working with cookies a lot I recommend a great Google Chrome plugin called EditThisCookie that will help see which cookies are being set and important information about each of them:

EditThisCookie Plugin

Upvotes: 1

Related Questions