I have a small problem with php cookies, this is the script I use to set cookies on my website visitors computer: <?php if ( $_POST["cookie"] != '' ) { $inTwoMonths = 60 * 60 * 24 * 60 + time(); setcookie('name', date("G:i - m/d/y"), $inTwoMonths); } ?> <?php if(!isset($_COOKIE['name'])) { echo '<form action="" method="post"> <input type="hidden" value="1" name="cookie" id="cookie" /> <input type="submit" value="save cookie" /> </form>'; } else { echo "Welcome"; } ?> PHP: The real code is rather complicated but it's not important. Here is what I'm trying to do... When user click the "save cookie" button I should echo the "Welcome" text, shouldn't it? But it's displayed only after the next page load! I mean when the clicks the save cookies button than he should refresh the page again to see the Welcome text. How can I solve this problem? I placed the setcookie function above the code where the cookie is checked but it doesn't work. Any ideas? Thanks in advance
Works fine <?php if(!isset($_POST["cookie"])) { $inTwoMonths = 60 * 60 * 24 * 60 + time(); setcookie('name', date("G:i - m/d/y"), $inTwoMonths); } if(!isset($_COOKIE['name'])) { print <<<HERE <form action="" method="post"> <input type="hidden" value="1" name="cookie" id="cookie" /> <input type="submit" value="save cookie" /> </form> HERE; } else { echo "Welcome"; } ?> PHP:
A quick work around until you get something better <?php if ( $_POST["cookie"] != '' ) { $inTwoMonths = 60 * 60 * 24 * 60 + time(); setcookie('name', date("G:i - m/d/y"), $inTwoMonths); } ?> <?php if(!isset($_COOKIE['name'])) { echo '<form action="" method="post"> <input type="hidden" value="1" name="cookie" id="cookie" /> <input type="submit" value="save cookie" /> </form>'; } else { error_reporting(OFF); header( "Location: /" ) ; echo "Welcome"; } ?> PHP: