<?php
if(isset($_POST['logout']))
{
setcookie("logincookie", FALSE);
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
if(isset($_POST['login']))
{
setcookie("logincookie", $_POST['loginName'], time()+3600); // expire in 1 hour
header("Location: " . $_SERVER['PHP_SELF']);
exit;
}
if(isset($_COOKIE['logincookie']))
{
echo "You are logged in as " . $_COOKIE['logincookie'] . ".";
?>
<hr>
<form action=<? echo $_SERVER['PHP_SELF']; ?> method=post>
<input type=hidden name=logout>
<input type=submit name=submit value="Log out">
</form>
<?
}
else
{
echo "You are not logged in, please enter your name:";
?>
<form action=<? echo $_SERVER['PHP_SELF']; ?> method=post>
<input type=text name=loginName>
<input type=hidden name=login>
<input type=submit name=submit value="Log in">
</form>
<?
}
?>
This code actually works the way I want it to. However, there are a few things about it that I think shouldn't work. I need your help to understand what's going on here.
After the user inputs his/her name into the text box and the submit button ("Log in") is pressed, shouldn't there be an infinite loop because of the second if statement? Doesn't header("Location: " . $_SERVER['PHP_SELF']); cause the whole page to reload without changing the status of the 'login' variable? If that's the case, then this if statement should run every single time the page is reloaded.
Why is it that if you click on the submit button ("Log in") button without writing something in the text box (look in the last else statement), the second if statement does not run? Shouldn't <input type=hidden name=login> create or set a "login" variable independent of whether the "loginName" text box was filled?
Any help would be appreciated.
Thanks
DJ