Хорошо, вот простой логин, который не предназначен для реального использования. Пожалуйста, прочитайте комментарии, включенные в код, чтобы увидеть, что я должен сказать о каждом. Выполнение входа в систему довольно сложно по ряду причин, поэтому этот пример предназначен не для демонстрации реальной работающей кодовой базы, а для очень простой проверки имени пользователя / пароля.
Проблемы безопасности, связанные с более сложным использованием, возможно, выходят за рамки этого ответа, но приведенный ниже код - это способ, которым я бы истолковал то, что вы опубликовали выше, не вдаваясь в подробности (вплоть до возможного затруднения понимания самые простые шаги, происходящие).
Дайте мне знать, если у вас есть какие-либо вопросы. Чтобы увидеть форму в действии, проверьте:
http://jfcoder.com/test/simplelogin.php
Также для простоты я использую синтаксис HEREDOC в PHP вместо строк в кавычках. Чтобы узнать больше об этой иногда удобной форме, см.
http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc.
<html>
<head>
<style type="text/css">
.error {
color: red;
}
</style>
</head>
<body>
<?php
// Note, in most cases you will set a SESSION variable
// of $_SESSION['loggedin'], which would require you to
// use session_start() before you access any session
// variables.
// Note, this defaults to false.
$loggedin = false;
// If I get an error, I will put it in this variable.
$error = '';
// If the username is provided, run the code. Otherwise,
// act as if the login form was not submitted. This makes
// a hidden `submitted` value superfluous, and guarantees
// your users at least provide a username.
if ($_POST['username']) {
// NOTE!!! In mose cases, you're querying a database
// for a username/password match. In PHP, this often
// means a MySQL query. DO NOT USE THE BELOW IF YOU
// ARE DOING SO!!! This will allow what's called a
// SQL injection. You MUST wash your data with something
// like mysql_real_escape_string() for the $_POST
// values (NEVER trust submitted data, always validate
// and escape as necessary), or use the PHP PDO library.
// In this example, though, I use a switch to check the
// values for exact matches, which means I do not need
// to escape (and mysql_real_escape_string() requires
// a database connection to use).
$username = $_POST['username'];
$password = $_POST['password'];
// Here, I check if the username and password match.
// This is, of course, hardcoded, but to match your
// attempt, I chose to keep the form, although you
// rarely see this in use in the real world.
switch ($username) {
// My one case. For each additional user, you
// would need to add a new entry with password
// check. And I set my error text according to
// the result of the code.
case 'user':
if ($password === 'abc123') {
$loggedin = true;
} else {
$error = 'Username/Password did not match.';
}
break;
default:
// Note, I don't give a descriptive error
// here. If someone reports this error, I
// know what may have gone wrong, but the
// user is not told the username does not
// exist.
$error = 'Unknown error. Try again.';
}
}
// I will only show the welcome message if the user has
// successfully logged in.
if ($loggedin === true) {
echo <<<HTML
<h1>Welcome!</h1>
<p>Thank you for logging in $username</p>
HTML;
} else {
// If an error text is set, display that error.
if ($error != '') {
$error = "<h4>Login error</h4><p class='error'>$error</p>";
}
// Here's my form, only shown if the user has not
// successfully logged in (note, this is only a one-
// time check when the POST data is submitted; I
// would need to use sessions to "remember" the requestor
// had logged in across page accesses.
echo <<<FORM
<h1>Login Form</h1>
<form action="simplelogin.php" method="POST">
$error
<p><label>Username: <input type="text" name="username"/></label></p>
<p><label>Password: <input type="password" name="password"/></label></p>
<p><input type="submit" value="Login"/> <input type="reset"/></p>
</form>
FORM;
}
?>
</body>
</html>