Как я могу отредактировать ошибки формы этого сценария входа в PHP для вывода ошибки на исходную страницу? - PullRequest
0 голосов
/ 18 октября 2011

Я просматривал следующее руководство по входу в 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
}

?>

Ответы [ 2 ]

1 голос
/ 18 октября 2011

Не используйте die() для выхода с ошибками.Вместо этого соберите ваши сообщения об ошибках в одну переменную, которую вы можете отобразить над формой.

// Initialize an empty container for all the errors
$errors = "";

if(!$_POST['username'] || !$_POST['password'] || !$_POST['firstname'] || !$_POST['lastname'] || !$_POST['email']){
  // Don't use die()
  //die('You didn\'t fill in a required field.');

  // Instead add this error to the $errors string.
  $errors .= "You didn\'t fill in a required field.<br />\n";
}

// Do the same for all the error conditions...

Проверьте, нет ли ошибок, прежде чем выполнять сеанс и работу с базой данных:

// 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;
}

Тогда вместо этогоотображения формы только внутри else, измените ее условие, чтобы проверить, не было ли сообщение отправлено, или $errors не пусто (т. е. ранее были ошибки).

if (!empty($errors) || !isset($_POST['submit'])) {
   // Display all the accumulated error messages (if there were any)
   echo $errors;

   // Display your form.
   // form stuff....
}

Еще одно замечание о внедрении SQL ... magic_quotes_gpc в наши дни не часто встречается.Вместо addslashes() обычной практикой является использование mysql_real_escape_string().

// Instead of this....
if(!get_magic_quotes_gpc()){
  $username = addslashes($username);
}

// Do this...
$username = mysql_real_escape_string($username);

. Делайте то же самое, где бы вы ни передавали значение $_POST (или GET, Cookie или другой ввод пользователя) в ваш SQLзапрос.

0 голосов
/ 18 октября 2011

Как насчет того, чтобы позволить самому PHP-сценарию распечатать форму входа?Затем вы можете распечатать дополнительную информацию, такую ​​как ошибки.

<html>
<head>
</head>
<body>

<?php

if(!isset($_GET['login']))
{
    //Print out the login form.
}
else
{
    //Check the login, if any errors occurs, print errors along with form.
}

?>

</body>
</html>

Имейте в виду, чтобы действие формы указывало на вашу страницу входа.

<form name="login" action="index.php" method="get">
Username: <input name="username" type="text" />
<br />
Password: <input name="password" type="password" />
<br />
<input type="submit" value="Login" />
</form>

Измените index.php настраница входа.

Что вы думаете?

Редактировать:

Я не проверял ваш код на наличие ошибок или потенциальных утечек, я только что ответил на ваш вопрос.

...