Search code examples
phpcookiessetcookie

PHP cookie will not set until the page reloads TWICE. What's going on?


Okay, here's a strange one. I'm attempting to deal with my first login system so bear with me.

There are 2 pages. PageA.php has the login form. Fill out the form and submit to PageB.php. PageB runs check against database, retrieves results, and sets cookie with value of username. PageB then uses header('location:PageA.php') to redirect back to PageA where PageA should HYPOTHETICALLY see that there is a set cookie, and change to do something useless and stupid (i.e. echo "Welcome back, username"). BUT the problem is here. Everything goes according to plan, except for that damn welcome back statement. For some reason, the cookie did not set. Or so I think. Then I go back to the url address, retype the url in my browser, hit enter, and then voila. The cookie is now recognized and everything works beautifully. It even works such that if you were to then logout and log back in, you would not need to do the reload.

In addition, the login ALSO works if you simply enter the information twice (i.e. it fails the first time, then you do it again immediately on PageA and it then works). Here's the relevant code:

PageA.php :

    <?php if(empty($_COOKIE['user'])){?>
        <form action="PageB.php" method="get">

        <input onfocus="this.value='';" maxlength="35" type="text" class="username" value="Username" name="username" />

        <input onfocus="this.value='';" maxlength="12" type="password" class="username" value="Password" name="password"/>


        <input type="image" id="login" src="Images/home/login_button.png" />
        </form>
        <?php }
        else {

            echo "<div id='welcome'>Welcome, ".$_COOKIE['user']."!</div>

        ";
        }?>

PageB.php :

$query="SELECT * FROM users where username='".$user."' and password='".$pw."' LIMIT 1";
$result=mysql_query($query,$con);

$num_rows = mysql_num_rows($result);

if($num_rows>0){

    while($row = mysql_fetch_array($result)){

        $username=$row['username'];

    }

    if(isset($_COOKIE['user'])){

        setcookie('user',$username,time()-2000);

    }

    setcookie('user',$username,time()+3600*168,"/");

}
mysql_close();

header('location:PageA.php');

What's even stranger is that I have no issues on the localhost, only when it is put online (Bluehost). Any insight would be greatly appreciated! Thank you in advance.

EDIT: I had forgotten to mention that PageA is the index (so actually named index.php). My header(location) actually redirects to the url (e.g. header('location:http://www.domainname.com'). However I now learned that the whole process works when I redirect to index.php instead of the domain name. But now I have that ugly "/index.php" in the url.


Solution

  • Your code looks OK to me. Output of PageA probably gets cached by a browser. Try adding some additional headers to PageA (remember to add them before anything else is outputted):

    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    

    They should prevent browser from caching.


    Also, you are changing the same cookie twice in one request (in some cases) here:

    if(isset($_COOKIE['user'])){
    
        setcookie('user',$username,time()-2000);
    
    }
    
    setcookie('user',$username,time()+3600*168,"/");
    

    This should be no issue but it doesn't make sense - first request will be overwritten by the second one.