Я просматривал следующее руководство по входу в PHP: http://www.evolt.org/node/60265 и в конечном итоге постараюсь развить его особенности, однако сначала я застрял в одном.У меня есть скрипт, работающий на моем тестовом сайте, я могу успешно зарегистрироваться и войти в систему.Однако проверка ошибок - это то, о чем я беспокоюсь, например, если пользователь не заполняет обязательное поле, на пустой веб-странице отображается ошибка «Вы не заполнили обязательную форму» - как я могу получитьэто для отображения на той же странице, что и форма (после отправки).
Редактировать: Спасибо, Майкл, я обновил свой код в соответствии с вашим ответом, но думаю, что я неправильно понял или сделал ошибку где-то, как сейчас мойстраница пустаЯ просматривал это несколько раз, но все еще не уверен.
Обновлен код ...
<?php
session_start();
include('./templates/dbconnect.php');
global $logged_in;
/**
* Returns true if the username has been taken
* by another user, false otherwise.
*/
function usernameTaken($username){
global $con;
if(!get_magic_quotes_gpc()){
$username = addslashes($username);
}
$query = "select username from users where username = '$username'";
$result = mysql_query($query,$con);
return (mysql_numrows($result) > 0);
}
/**
* Inserts the given (username, password) pair
* into the database. Returns true on success,
* false otherwise.
*/
function addNewUser($username, $password, $firstname, $lastname, $email){
global $con;
$query = "INSERT INTO users(username, password, firstname, lastname, email) VALUES ('$username', '$password', '$firstname', '$lastname' , '$email')";
return mysql_query($query,$con) or die(mysql_error());
}
/**
* Displays the appropriate message to the user
* after the registration attempt. It displays a
* success or failure status depending on a
* session variable set during registration.
*/
function displayStatus(){
$uname = $_SESSION['reguname'];
if($_SESSION['regresult']){
?>
Registered!
Thank you <b><?php echo $uname; ?></b>, your information has been added to the database, you may now <a href="main.php" title="Login">log in</a>.
<?php
}
else{
?>
Registration Failed
We're sorry, but an error has occurred and your registration for the username <b><? echo $uname; ?></b>, could not be completed.<br>
Please try again.
<?php
}
unset($_SESSION['reguname']);
unset($_SESSION['registered']);
unset($_SESSION['regresult']);
}
if(isset($_SESSION['registered'])){
/**
* This is the page that will be displayed after the
* registration has been attempted.
*/
?>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="container">
<?php include('./templates/header.php'); ?>
<div class="content">
<?php displayStatus(); ?>
</div>
<div class="footer">Copyright © 2011 Richard Day.</div>
</div>
</body>
</html>
<?php
return;
}
/**
* Determines whether or not to show to sign-up form
* based on whether the form has been submitted, if it
* has, check the database for consistency and create
* the new account.
*/
if(isset($_POST['submit'])){
/* Make sure all fields were entered */
// Initialize an empty container for all the errors
$errors = "";
if(!$_POST['username'] || !$_POST['password'] || !$_POST['firstname'] || !$_POST['lastname'] || !$_POST['email']){
// die('You didn\'t fill in a required field.');
$errors .= "You didn\'t fill in a required field.<br />\n";
}
/* Spruce up username, check length */
$_POST['username'] = trim($_POST['username']);
if(strlen($_POST['username']) > 16){
//die("Sorry, the username is longer than 16 characters, please shorten it.");
$errors .= "Sorry, the username is longer than 16 characters, please shorten it.<br />\n";
}
/* Check if username is already in use */
if(usernameTaken($_POST['username'])){
$use = $_POST['username'];
$errors .="Sorry, the username: <strong>$use</strong> is already taken, please pick another one.";
//die("Sorry, the username: <strong>$use</strong> is already taken, please pick another one.");
}
// No previous errors, so it's safe to store the variables.
if (empty($errors)) {
/* Add the new account to the database */
$md5pass = md5($_POST['password']);
$_SESSION['reguname'] = $_POST['username'];
$_SESSION['regfirstname'] = $_POST['firstname'];
$_SESSION['reglastname'] = $_POST['lastname'];
$_SESSION['regemailname'] = $_POST['email'];
$_SESSION['regresult'] = addNewUser($_POST['username'], $md5pass, $_POST['firstname'], $_POST['lastname'], $_POST['email']);
$_SESSION['registered'] = true;
echo "<meta http-equiv=\"Refresh\" content=\"0;url=$_SERVER[PHP_SELF]\">";
return;
}
?>
<html>
<head>
<title>Register</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="container">
<?php include('./templates/header.php'); ?>
<div class="content">
<?php
if (!empty($errors) || !isset($_POST['submit'])) {
// Display all the accumulated errors (if any)
echo $errors;
/**
* This is the page with the sign-up form, the names
* of the input fields are important and should not
* be changed.
*/
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table align="center" border="0" cellspacing="0" cellpadding="3">
<tr><td><b>Register</b></td></tr>
<tr><td>Username:</td><td><input type="text" name="username" maxlength="16"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password" maxlength="30"></td></tr>
<tr><td>First name:</td><td><input type="text" name="firstname" maxlength="32"></td></tr>
<tr><td>Last name:</td><td><input type="text" name="lastname" maxlength="32"></td></tr>
<tr><td>E-mail:</td><td><input type="text" name="email" maxlength="64"></td></tr>
<tr><td colspan="2" align="right"><input type="submit" name="submit" value="Register"></td></tr>
</table>
</form>
</div>
<div class="footer">Copyright © 2011 Richard Day.</div>
</div>
</body>
</html>
<?php
}
?>