Problem with PHP cookies

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
tomface
Forum Newbie
Posts: 7
Joined: Wed Apr 08, 2009 4:37 pm

Problem with PHP cookies

Post 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.
Reviresco
Forum Contributor
Posts: 172
Joined: Tue Feb 19, 2008 4:18 pm
Location: Milwaukee

Re: Problem with PHP cookies

Post by Reviresco »

It looks like the login script is in a different directory. Set the path to "/":

Code: Select all

 
setcookie('user', $username, $expire, "/");
 
tomface
Forum Newbie
Posts: 7
Joined: Wed Apr 08, 2009 4:37 pm

Re: Problem with PHP cookies

Post 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?
Reviresco
Forum Contributor
Posts: 172
Joined: Tue Feb 19, 2008 4:18 pm
Location: Milwaukee

Re: Problem with PHP cookies

Post 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
Post Reply