Hi,

I'm trying to write a short/simple function that will get the information that is in a COOKIE and return it.

I have a COOKIE that is called auth. This COOKIE is properly set as I can do an echo $_COOKIE; and it will show the proper number. The problem arises when I try to put it into a function. This is the code that I have to try and access a function and return the auth info:

<?php
   function getAuth()
   {
       return $_COOKIE['auth'];
   }
?>

I get absolutely nothing returned to me. I have also tried putting it into a local variable first:

<?php
    function getAuth()
   {
      $auth = $_COOKIE['auth'];
      return $auth;
   }
?>

but still nothing is returned. The file that I have this function in is included in the page that I'm trying to call it from, so the function is global and shouldn't have any problem accessing/returning the cookie information.

Any help is very appreciated, thank you.

Yes the cookie is set. I have tried just echoing the cookie as said in the post. I receive the correct information, but when I try to get the cookie through a return statement in a function I get zilch.

I think you will find that $_COOKIE, $_POST and $_GET (and others?) are not super-globals, therefore you must put global $_COOKIE; inside functions (which have their own scope).

Airshow

No according to PhP documentation $_COOKIE is a super-global.

Any other suggestions?

This works for me:

<?php
if (!isset($_COOKIE['auth'])) setcookie("auth","this is the value");
else echo getCookieValue("auth");

function getCookieValue($cookie) {
    return $_COOKIE[$cookie];
}
?>

No according to PhP documentation $_COOKIE is a super-global.

Beg pardon, it's the old, deprecated $HTTP_COOKIE_VARS etc. that were not super globals.

Airshow

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.