Page 1 of 1

Problem with PHP cookies

Posted: Wed Apr 29, 2009 5:45 am
by tomface
For some reason im having a great deal of problems with using cookies on my website. I have a login system which i initially set to use sessions, but decided to use cookies as sessions was a bit glitchy. The order of my website goes:

Login form > Check Login Script > Login Success Script > index.htm

on the first script, this is code that sets the cookie:

Code: Select all

        // Register $myusername, $mypassword and redirect to file "login_success.php"
        $expire=time()+60*60*24*5;
        setcookie('user', $username, $expire);
        header("location:login_success.php");
And this is the piece of code on each page that checks that the cookie is there:

Code: Select all

<?php
 
if(!isset($_COOKIE['user']))
    {
    header("location:login/main_login.htm");
    }
 
?>

Now for some reason, it will go to the Login Success page, and not have a problem even though that page has the cookie checking code on it. However, when the Login Success page then redirects to the index.htm page, it goes straight back to the login form, thinking the cookie's not there. The second bit of code is identical on all the pages i have protected by the login system.

Thanks in advance.

Re: Problem with PHP cookies

Posted: Wed Apr 29, 2009 11:56 am
by Reviresco
It looks like the login script is in a different directory. Set the path to "/":

Code: Select all

 
setcookie('user', $username, $expire, "/");
 

Re: Problem with PHP cookies

Posted: Wed Apr 29, 2009 2:51 pm
by tomface
Okay thanks for that. Think the problem may be that my website has a few organised sub folders, instead of just having all the html files in one folder. How can i get a cookie to cover the whole website?

Re: Problem with PHP cookies

Posted: Wed Apr 29, 2009 4:03 pm
by Reviresco
Add the domain with a dot before it:

Code: Select all

 
setcookie('user', $username, $expire, "/", ".example.com");
 
Info:
http://us.php.net/setcookie