Trouble with setcookie()
Posted: Thu Jul 10, 2008 5:10 am
Code: Select all
<?php
$username = "username";
$password = "password";
$randomword = "something";
if (isset($_COOKIE['MyLoginPage'])) {
if ($_COOKIE['MyLoginPage'] == md5($password.$randomword)) {
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="-1" />
<meta http-equiv="Cache-Control" content="no-cache" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>
Title
</title>
</head>
<body>
<p> LOGIN WAS SUCCESSFUL </p>
<br />
<p> cookie MyLoginPage = <?php echo $_COOKIE["MyLoginPage"]; ?> </p>
<br />
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=logout" method="post">
<input type="submit" value="logout" name="Logout?">
</form>
<br />
</body>
</html>
<?php
exit;
} else {
echo "<p>Bad cookie. Clear please clear them out and try to login again.</p>";
exit;
}
}
if (isset($_GET['p']) && $_GET['p'] == "login") {
if ($_POST['name'] != $username) {
echo "<p>Sorry, that username does not match. Use your browser back button to go back and try again.</p>";
exit;
} else if ($_POST['pass'] != $password) {
echo "<p>Sorry, that password does not match. Use your browser back button to go back and try again.</p>";
exit;
} else if ($_POST['name'] == $username && $_POST['pass'] == $password) {
setcookie('MyLoginPage', md5($_POST['pass'].$randomword));
header("Location: $_SERVER[PHP_SELF]");
} else {
echo "<p>Sorry, you could not be logged in at this time. Refresh the page and try again.</p>";
}
}
// TROUBLING 'IF' BLOCK - This is where the issue is
if (isset($_GET['p']) && $_GET['p'] == "logout") {
setcookie('MyLoginPage', '', time()-3600);
header("Location: $_SERVER[PHP_SELF]");
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>?p=login" method="post"><fieldset>
<label><input type="text" name="name" id="name" /> Name</label><br />
<label><input type="password" name="pass" id="pass" /> Password</label><br />
<input type="submit" id="submit" value="Login" />
</fieldset></form>The logging in part was fine. But, when I click logout, the html block ('LOGIN WAS SUCCESSFUL') reloads with the cookie having the old value. Now, I have read that setcookie() should precede any html (and space) code. I dont see anything of that sort getting violated in my code (on logout). Also, if the login block gets executed without any trouble, why doesn't the logout block?
Also, when I cut and pasted the 'TROUBLING IF BLOCK' at the very top of all the codes (even before $username=...), it works as it should - ie, as soon as I click the logout button, the login form loads.
Thanks,