I’m designing a log in system as a personal project and I’m trying to store the user’s email and password hash (should I store the plain text password instead?) in cookies so that the site knows what account the user is logged into.
The trouble is, as soon as I put my setcookie(); commands in an if statement, they stop working. I know the if statement is being reached because other code is being called from within it, but it’s as if the setcookie() is being ignored.
Here’s the code:
<?php
$email = $_POST[email];
$password = $_POST[password];
$passwordHash = sha1($password);
$dbhost = "localhost";
$dbuser = "user";
$dbpass = "password";
$dbname = "db";
mysql_connect($dbhost,$dbuser,$dbpass)
or die("Error: Failed to connect to database");
mysql_select_db($dbname)
or die("Error: Failed to select databse");
$query = "SELECT * FROM users WHERE user = '$email'";
$sql = mysql_query($query);
while($r = mysql_fetch_array($sql)) {
if($passwordHash == $r[passwordhash]) {
setcookie("Email", $email, time()+3600);
setcookie("PasswordHash", $passwordHash, time()+3600);
echo "added cookie";
}
else {
echo "Incorrect password";
}
}
?>
A cookie defined by setcookie is sent along with other headers (which must be sent before any output including whitespace). I think that the problem is here.
UPDATE
I’d try
header('Location: somepage.html')instead ofsetcookieto make sure if it is the culprit.