I have a site that allows users to sign in, and when they do I set a cookie. setcookie( "id", "$userid", time()+3600, "/", false); PHP: But on other pages like url.com/member I try this code: <?php if (isset($_COOKIE["id"])) echo "logged in"; else echo "logged out"; ?> PHP: Even though I just signed in it still sends me "logged out"
Which page set the cookie? Was the page that sets it an include and is included in this page? PHP can be tricky with cookies but what you are seeing is that the cookies are most likely being set on the same page. I would first use firefox development tools to establish if the cookie is set. Daniel
Like what Danny asked above, are 1.php and 2.php both called from the same request? e.g.: 1.php does a include('2.php') or require('2.php') or include_once('2.php') or require_once('2.php')? If the answer to the above is "yes", then that behaviour is expected. The way cookies work is, when browser sends a request to the web server, all cookies that match the domain and path of the requested page are sent to the server. On server site, with PHP these cookies can be accessed from the super-global variable $_COOKIE. If both 1.php and 2.php are executed from the same request, then what happens is: 1. When 1.php is requested, no cookie sent to server. So $_COOKIE is empty. 2. When 1.php sets the cookie, $_COOKIE is still empty, because $_COOKIE will only be updated when browser sends it in the HTTP header with a page request. 3. When 2.php is included from 1.php $_COOKIE is still empty. 4. If another page from the same domain is requested, $_COOKIE will then have the values set in 1.php.
If your site is not top-secret or something. Thats probably ok. But anyone can modify their cookies with one line of javascript in their addressbar and set the id to 'admin' or any other user's name to get free access. IMO, you may be better off using session variables. Read about it at: http://php.net/session You just have to put session_start() at the top of each PHP file. You can set the varibles like this: $_SESSION['id']=$userid; This variable can then be accessed in other PHP pages also using $_SESSION['id'] . The only condition is that you put session_start() at the top of that pages too. You can use session_destroy() in the logout section of your site. That was a brief summary of sessions. . Just look in google for 'PHP Sessions' or something like that and you will probably get loads of stuff. Hope that was helpful, Thomas