I was looking for a simple PHP script + form that routed users to specific URLs based on the username and password entered.
Code at the top of the page:
<?php
session_start();
$data=array("user1"=>array("url"=>"file1.php","password"=>"pass1"),
"user2"=>array("url"=>"file2.php","password"=>"pass2"));
if(isset($_POST['username']) && isset($_POST['password'])) {
if($data[$_POST['username']]['password'] == $_POST['password']) {
$_SESSION['username'] = $_POST['username'] . " " . $_POST['password'];
header('Location: ' . $data[$_POST['username']]['url']);
login('<p class="alert">Incorrect username or password.</p> ');
}
} else {
login();
}
?><?php
function login($response='Please enter your username and password.') {
?>
This is in the body:
<p><?=$response?></p>
<form action="" method="post">
<table width="400" border="0" cellspacing="0" cellpadding="4">
<tr>
<td width="90"><label class="loginform" for="username">Username:</label></td>
<td width="294"><input name="username" type="text" /></td>
</tr>
<tr>
<td><label for="password">Password:</label></td>
<td><input name="password" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</form>
<?php } ?>
This code works properly, but if a user enters an incorrect password, it redirects to a blank page (specifically, it only loads the page after the last:
<?php } ?>
I understand this code is not written well at all, so that is the first problem. I'd really love to see a well-written version (just to learn and study it). But if that's not possible, how would I correct this code so an incorrect password doesn't break the page?
It's odd, because if you enter nothing (just hit Submit), it says "Incorrect username or password", and if you just enter an incorrect username with no password, same thing. But with a username + wrong password, or only wrong password, it goes to the blank page.
Thanks in advance!