Forum Moderators: coopster
if(isset($username)) {?> ...the main page I want to display - including
"welcome back, <? echo $name?> ... <? } else{ setcookie(username,$name,time()+$cookielife); ?> ...The page with the form, which has method="get" and action="index.php"....
<? } ?> Something is wrong here, because when I load the page, it asks me for my name, then I click submit, and the same page comes up and asks for my name again. However, if I click refresh or submit again, the correct page loads! What is making this happen? Different things happen when I shift the setcookie() around, am I putting it in the right place?
If you havenīt done it yet I suggest you read Marciaīs WebmasterWorld Welcome and Guide to the Basics [webmasterworld.com] post which contains a lot of helpful information.
Have you checked whether caching is an issue.
I got something similar to work using code along these lines:
disable_caching
if(name) {
setcookie
cookie = name
}
if(cookie) {
print cookie
} else {
print form
}
Andreas
To make the name appear on that page you need to use the value supplied by the submitted form. That is what the
cookie = name does in my pseudo code. Here is how the pseudo code would look like in real PHP code.
<?Andreas
# prevent caching
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
#
# If the form is submitted $_GET['name'] will contain the name
if($_GET['name']) {
# the cookie will be added to the response header which
# is sent back to the browser along with this page
setcookie('username', $_GET['name']);
# since the cookie does not exist on the client side yet
# we set the variable to the submitted value
$_COOKIE['username'] = $_GET['name'];
}
# if we have a username, display it
if(isset($_COOKIE['username'])) {?>
<p>Hallo <?=$_COOKIE['username']?></p>
<?}
# otherwise display the form to get the username
else
{?>
<form><input name="name" type="input"><input type="submit"></form>
<?}?>