I am trying to setup a simple PHP login script that redirects after successful login. The problem is that the header call only works after a successful login followed by a manual refresh. The only answer for this problem I have found on SO is "do not echo content before the call to header", however I do not believe I am. I did read that session_start sends headers but if I move that to after the call to isset, the page doesnt redirect after refresh, leading me to believe the session variable is not set.
<?php session_start();
if(isset($_SESSION['logged']))
{
header("Location: index.html");
exit;
}
function BuildLogin(){
include("passwords.php");
if ($_POST["ac"]=="log") { /// do after login form is submitted
if ($USERS[$_POST["username"]]==$_POST["password"]) {
$_SESSION["logged"]=$_POST["username"];
} else {
echo 'Incorrect username/password. Please, try again.';
};
};
if (!array_key_exists($_SESSION["logged"],$USERS)) {
echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';
echo 'Username: <input type="text" name="username" />';
echo 'Password: <input type="password" name="password" />';
echo '<input type="submit" value="Login" />';
echo '</form>';
};
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" http-equiv="x-ua-compatible" content="IE=9">
<title>File Management</title>
<style type="text/css">/* IE has layout issues when sorting (see #5413) */
.group { zoom: 1 }
body{
padding:0px 25px 25px 25px;
}
#content {
background-color:#989898;
box-shadow: 0px 10px 20px rgba(0,0,0,.5);
border-top-right-radius: 4px;
border-top-left-radius: 4px;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
padding:25px 25px 25px 25px;
height:auto;
overflow:auto;
}
</style>
</head>
<body>
<div id="content">
<?php BuildLogin(); ?>
</div>
</body>
</html>
Thanks to TheBeacon for the solution. Here is the updated version of the PHP
<?php
session_start();
if (isset($_POST["ac"]) && !empty($_POST) && $_POST["ac"]=="log") {
include("passwords.php");
if ($USERS[$_POST["username"]]==$_POST["password"]) {
$_SESSION["logged"]=$_POST["username"];
header('Location: index.html');
};
};
function BuildLogin(){
include("passwords.php");
if (isset($_POST["ac"]) && !empty($_POST) && $_POST["ac"]=="log") {
echo 'Incorrect username/password. Please, try again.';
};
if (!array_key_exists($_SESSION["logged"],$USERS)) {
echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> ';
echo 'Username: <input type="text" name="username" />';
echo 'Password: <input type="password" name="password" />';
echo '<input type="submit" value="Login" />';
echo '</form>';
};
}
?>