Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top