[英]How can I edit the form errors of this PHP login script to output the error on the original page?
I've been looking at the following PHP login tutorial:http://www.evolt.org/node/60265 and will eventually look to develop the features of this further, however I am stuck on one thing first. 我一直在看下面的PHP登录教程:http://www.evolt.org/node/60265,最终会进一步开发它的功能,但是我首先要坚持一件事。 I have got the script working on my test site, I can register and login successfully.
我已经在测试站点上运行了脚本,我可以成功注册和登录。 However the error checking is what I have a gripe about, for example, if a user fails to fill in a required field, the error 'You didn't fill in a required form' is displayed on a blank webpage - how can I get this to display on the same page as the form (once submitted).
但是,错误检查正是我所要解决的问题,例如,如果用户未能填写必填字段,则空白网页上会显示错误“您未填写必填表格”-如何获取与表单(提交后)显示在同一页面上。
Edit: Thanks Michael, I've updated my code as per your answer but think I've misunderstood or made a mistake somewhere as now my page is blank. 编辑:谢谢迈克尔,我已经按照您的回答更新了代码,但由于我的页面空白,因此我误解或在某个地方犯了错误。 I've looked over it a few times but i'm still unsure.
我已经看过几次了,但我仍然不确定。
Updated code... 更新的代码...
<?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
}
?>
Don't use die()
to exit with errors. 不要使用
die()
退出并返回错误。 Instead, accumulate your error messages into a single variable that you can display above the form. 而是,将错误消息累积到单个变量中,即可在表格上方显示。
// 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...
Test for no errors before doing your session & database activity: 在进行会话和数据库活动之前,请测试是否没有错误:
// 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;
}
Then instead of displaying the form only inside the else
case, change its condition to test if either the post hasn't been submitted, or $errors
is nonempty (ie there were errors previously). 然后,代替仅在
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....
}
A further note about SQL injection... magic_quotes_gpc
isn't encountered often these days. 关于SQL注入的进一步说明...
magic_quotes_gpc
。 Instead of addslashes()
common practice is to use mysql_real_escape_string()
. 代替
addslashes()
常见做法是使用mysql_real_escape_string()
。
// Instead of this....
if(!get_magic_quotes_gpc()){
$username = addslashes($username);
}
// Do this...
$username = mysql_real_escape_string($username);
Do the same thing anywhere you are passing a $_POST
(or GET or Cookie, or other user input) value into your SQL query. 在将
$_POST
(或GET或Cookie或其他用户输入)值传递到SQL查询中的任何地方, $_POST
执行相同的操作。
How about letting the PHP script itself print out the login form? 如何让PHP脚本本身打印出登录表单? Then you can print out additional information like errors.
然后,您可以打印出其他信息,例如错误。
<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>
Keep in mind to make the action of the form point to your login page. 请记住,使表单的操作指向您的登录页面。
<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>
Change index.php to the login page. 将index.php更改为登录页面。
What do you think? 你怎么看?
Edit: 编辑:
I didn't check your code for errors or potential security leaks, I just answered your question. 我没有检查您的代码是否有错误或潜在的安全漏洞,我只是回答了您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.