faqts : Computers : Programming : Languages : PHP : Common Problems : Cookies

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

25 of 28 people (89%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

Why can't I see the contents of my cookie in a function?

Jul 5th, 1999 17:22
Nathan Wallace, Nathan Wallace


PHP treats every variable as local to the function unless you specify it
as global.  Thus, you cannot access $HTTP_COOKIE_VARS in a function
unless you declare it as global inside that function.

This should work:

    function ReadCookie($name) {
        global $HTTP_COOKIE_VARS;
        return $HTTP_COOKIE_VARS[$name];
    }

Similarly the cookie is not accessable by name unless you declare it as
global.  In this case what we actually want is the variable that holds
the cookie (the one called $name) to be global, so we have to globalize
the variable variable...

    function ReadCookie($name) {
        global $$name
        return $$name;
    }