0

After clearing my cookies so I could test it fresh, I tried making a simple form to set a cookie. After typing in the text form and pressing the submit button, however, it seems to set the cookie, but fails to recognize it until you press submit again (with nothing written in the form). Sounds weird, but you can try it for yourself. I narrowed the code to make it simple.

<?php

if(isset($_GET['email'])){
    $email = $_GET['email'];
    $time = time() + 60;
    setcookie('email',$email,$time);
    $cookie = $_COOKIE['email'];
    echo 'Cookie successfully created: '.$cookie.'<br><br>';
}

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

echo 'Hello there!';

}else if(!isset($_COOKIE['email'])){

echo '<form action="test.php" method="GET">
<p>Please provide your email address</p>
<input type="text" name="email" size="25" /><input type="submit" value="Submit" />
</form>';

}

?>

Some simple thing I'm missing. Any clues?

adamdesign
  • 190
  • 1
  • 18
  • 2
    "Once the cookies have been set, they can be accessed _on the next page load_ ..." (emphasis mine) [doc](http://php.net/setcookie) – Wiseguy Dec 27 '13 at 22:10

1 Answers1

1

Cookies are only written to the browser as the browser loads the page the first time. So the second check would only work on the next page load.

Best way to deal with this would be something like:

<?php

if(isset($_GET['email'])){
    $email = $_GET['email'];
    $time = time() + 60;
    setcookie('email',$email,$time);
    $cookie = $_COOKIE['email'];
    echo 'Cookie successfully created: '.$cookie.'<br><br>';
}

if(isset($_COOKIE['email']) || isset($_GET['email'])){

echo 'Hello there!';

}else if(!isset($_COOKIE['email'])){

echo '<form action="test.php" method="GET">
<p>Please provide your email address</p>
<input type="text" name="email" size="25" /><input type="submit" value="Submit" />
</form>';

}

?>

Checking for the _GET variable that sets the cookie in the first place would allow your script to work on the first and subsequent page loads.

steve
  • 2,469
  • 1
  • 23
  • 30
  • the else if could potentially change to just an else too - depending on if you're planning on having any other conditions in the finalised script. – steve Dec 27 '13 at 22:12