You can't send headers after printing html, so this function won't work. The workaround may be:
<?php
## Check for manipulation ##
if($login_result != "") {
die("Go hack somewhere else!");
}
## Functions ##
function login($username, $password) {
$user = "username";
$pass = "password";
if ($username != $user && $password != $pass) {
$login_action = "fail";
} else {
$login_action = "true";
}
return $login_action;
}
function page($page) {
header("location:$page");
}
## Page starts ##
if($username != "") {
$login_result = login($username, $password);
if($login_result == "true") {
page("index.php");
} else {
print ("Login Failure! Either the username or password you entered are incorrect.<br>Please try again.");
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Enter your username and password:</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script language="JavaScript" type="text/JavaScript">
<!--
function validation(form) {
if ((form.username.value == "") || (form.password.value == "")) {
alert("Please enter your username or password.");
}
else {
form.submit();
}
}
//-->
</script>
</head>
<body>
<form action="login.php" method="POST" onsubmit="validation(this);return false;">
<input type="text" name="username">
<br>
<input type="password" name="password">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
This is meant as a workaround/example for the header() only! Not as any protection for your page 😃
If you're gonna protect your page, you need to either set cookies or sessions to check for auth!
A "secret" page may never be considered secure: what if the nice Mr. Google Robot comes along, indexing your page-to-be-protected? Your secrets will then be availiable at a search on the Google engine 😉 :eek:
I'll advise you to read more about cookies/sessions before you publish:
http://www.php.net/manual/en/function.setcookie.php
http://www.php.net/manual/en/ref.session.php
I've made a reasonably secure login here, but it requires both cookies and Javascript to be enabled:
http://www.publicator.no/php_net/login/
It's also due for an upgrade - soon 😃
knutm