1

I have 2 files, index.php and content.php ...

I am setting a cookie on the content.php but when i am trying to retrieve that cookie in index.php, it says undefined index...

I dnt know the reason of this error !

I am using this code for setting the cookie-

$loader = $_GET['id'];
$expire=time()+60*60*24*365;
setcookie("loader", $loader, $expire);

and this for retriving-

if (isset($_COOKIE["loader"])) echo $_COOKIE["loader"];
else echo "no cookie found !";

Please Help Me Guys !

NullPoiиteя
  • 56,591
  • 22
  • 125
  • 143
PHP kid
  • 55
  • 9

2 Answers2

1

Edit2:

If you get this error 'Undefined Index' that means that your $_GET['id'] isn't set properly. Make sure you've set the $_GET['id']; when setting the cookie.

$loader = $_GET['id'];
$expire=time()+60*60*24*365;

if(isset($_GET['id'])){
setcookie("loader", $loader, $expire, '/');
}else{
echo 'no cookie set';

Edit:

when you've set the cookie you first have to refresh the page BEFORE you read it. otherwise the cookie isn't sent in the header.


Just add a path to your cookie like this:

$loader = $_GET['id'];
$expire=time()+60*60*24*365;
setcookie("loader", $loader, $expire, '/');

NOTE: I've added the '/'

Hope it helps.

Kees Sonnema
  • 5,759
  • 6
  • 51
  • 106
  • This shouldn't be needed if both scripts are in the same directory. – Barmar Jun 04 '13 at 06:57
  • I am almost 100% sure it has to do with the path. because the browser uses the script uri, so you can always see the cookie if set. http://stackoverflow.com/a/7394471/1379394 – Kees Sonnema Jun 04 '13 at 07:09
  • @KeesSonnema as i have in the above replies, i have succesfully set the `cookie` i can view it in the **opera's cookie manager**... – PHP kid Jun 04 '13 at 07:16
  • As i said. the browser can always read the cookie even if it is not available in the views. that's because it is using the script uri. – Kees Sonnema Jun 04 '13 at 07:17
  • 1
    @KeesSonnema : i have set the `/path` and it worked... thanx bud ^_^ – PHP kid Jun 04 '13 at 07:27
1
if(isset($_REQUEST['id'])) {
    setcookie('loader',$_REQUEST['id'],time()+60*60*24*365, '/');   
} else {
    setcookie('loader','',time()-3600, '/');
    unset($_COOKIE['loader']);          
}


if(isset($_COOKIE['loader']) && $_COOKIE['loader'] != "") {     
    echo $_COOKIE['loader'];
} else {
   echo "no cookie found !";
}
  • i have successfully set the cookie, coz i can see it from the **opera's cookie manager** but when trying to get the data in the **index.php** then it says undefined index – PHP kid Jun 04 '13 at 07:04
  • @vikram This is working fine..i myself have tried it.It can be a problem of PHP Version.What version you are using? – Ritika Jain Jun 04 '13 at 08:34
  • i am using PHP Version 5.3.9, anyways Ritika i got my answer... thanx for commenting.... :-) – PHP kid Jun 05 '13 at 03:05