PHP验证表单

时间:2014-12-06 18:01:11

标签: javascript php forms

我一直在尝试从我的login.php获取验证消息,以显示在带有表单的页面上,我哪里出错了?我确实在某一点尝试使用JavaScript来显示信息而没有运气,它会一直显示,如下图所示。

我知道它可以添加到我想要的结果的同一页面中,但我正在尝试将其作为一个干净的页面,没有jQuery,最多的一些vanilla JavaScript。目的是让验证消息在表单上方,起初我正在思考跨度,但我不知道在哪里可以找到关于如何在停留在同一页面时从另一个文件输出结果的教程。

http://snag.gy/SI9lq.jpg

      <table border ='0'>
                <form action="login.php"  method="POST">
                    <tr><td>Username:</td> <td><input type="text" name="username" required></td></tr>
                    <tr><td>Password:</td> <td><input type="password" name="password" required></td><tr>
                    <tr><td><input button id="myBtn" type="submit" value="Log in"><td></tr>
                    <tr><td><a href='register.php'>Register</a></td></tr>
            </table> 




     <?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$errors = array();


if ($username&&$password)
{

$connect = mysql_connect("localhost","root","") or die ("Could not connect");
mysql_select_db ("login") or die ("Could not find database");

$query = mysql_query("SELECT * FROM users WHERE username ='$username'");

$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
    while ($row =mysql_fetch_assoc($query))
    {
        $dbusername = $row['username'];
        $dbpassword = $row['password'];
    }

    if ($username==$dbusername&&$password==$dbpassword)
    {
        echo header( 'Location: member.php' ) ;
        $_SESSION['username']=$dbusername;
    }
    else 
        echo"
         <script type=\"text/javascript\">
        window.onload = function latestNews(){
      var newPara = document.createElement('p');
      var add_news = document.createTextNode('Incorrect password');
      newPara.appendChild(add_news);
      var getSecond = document.getElementById('footer');
      document.body.insertBefore(newPara, getSecond);
    };
         </script>
    ";
}
else
    die("That user dosen't exist");

}

else
    die("Please enter a username and a password");
?>

修改

我试图添加JavaScript,虽然它具有相同的效果。

4 个答案:

答案 0 :(得分:3)

要显示简单的错误消息,只需在表单上方回显即可。看看是否有效

<?php

session_start();

$username = $_POST['username'];
$password = $_POST['password'];
$errors   = array();
$msg      = ""; //define an error msg variable


if (isset($_POST['username'], $_POST['password'])) {

    $connect = mysql_connect("localhost", "root", "") or die("Could not connect");
    mysql_select_db("login") or die("Could not find database");

    $query = mysql_query("SELECT * FROM users WHERE username ='$username'");

    $numrows = mysql_num_rows($query);
    if ($numrows != 0) {
        while ($row = mysql_fetch_assoc($query)) {
            $dbusername = $row['username'];
            $dbpassword = $row['password'];
        }

        if ($username == $dbusername && $password == $dbpassword) {
            echo header('Location: member.php');
            $_SESSION['username'] = $dbusername;
            $_SESSION['userid']   = $userid;
        } else
            $msg = "Incorrect password";
    } else
        $msg = "That user dosen't exist";

}

else
    $msg = "Please enter a username and a password";

?>


<div class='errorMsg'><?php echo $msg; ?></div>
  <form action="login.php" method="post"></form>
  <table border='0'>
    <tr>
      <td>Username:</td>
      <td><input name="username" required="" type="text"></td>
    </tr>

    <tr>
      <td>Password:</td>
      <td><input name="password" required="" type="password"></td>
    </tr>
    <tr>
      <td></td>
    </tr>
    <tr>
      <td><input id="myBtn" type="submit" value="Log in"></td>
      <td></td>
    </tr>
    <tr>
      <td>
        <a href='register.php'>Register</a>
      </td>
    </tr>
  </table>
  </form>

答案 1 :(得分:1)

如果你这样做

<?php
$connect = mysql_connect("localhost","root","") or die ("Could not connect");
mysql_select_db ("login") or die ("Could not find database");

session_start();
function output_errors($errors){
return '<ul class="a"><li><strong>'.implode('</li><li>', $errors) .'</strong></li></ul>';
}

$errors = array();

if(empty($_POST) === false) {
$required_fields = array('username', 'password');
foreach ($_POST as $key=>$value) {
if(empty($value) && in_array($key, $required_fields) === true){
$errors[] = 'user name and password is empty !';
break 1;
}
}
$username = $_POST['username'];
$password = $_POST['password'];
if(strlen($_POST['password']) < 5){
$errors[] = 'Your password must be at least 5 Characters.';
}
if ($username&&$password)
{

$query = mysql_query("SELECT * FROM users WHERE username ='$username'");

$numrows = mysql_num_rows($query);
if ($numrows !=0)
{
    while ($row =mysql_fetch_assoc($query))
    {
        $dbusername = $row['username'];
        $dbpassword = $row['password'];
    }

    if ($dbusername&&$password != $dbpassword) {
     $errors[] = "password wrong";  
    }
}
}
}
if(empty($_POST) === false && empty($errors) === true && $username==$dbusername&&$password==$dbpassword){
echo header( 'Location: member.php' ) ;
$_SESSION['username']=$dbusername;
exit();
}else if(empty($errors) === false){
echo output_errors($errors);
}
?>

              <table border ='0'>
                        <form action="login.php"  method="POST">
                            <tr><td>Username:</td> <td><input type="text" name="username" ></td></tr>
                            <tr><td>Password:</td> <td><input type="password" name="password" ></td><tr>
                            <tr><td><input button id="myBtn" type="submit" value="Log in"><td></tr>
                            <tr><td><a href='register.php'>Register</a></td></tr>
                    </table> 

答案 2 :(得分:1)

编写一个新的PHP程序,可能称为checker.php。 checker.php的工作是检查错误并提供成功&#34;页面,如果没有找到。但是,如果checker.php发现错误,它会设置一个PHP变量$error = TRUE;(您可以使用您希望能够报告多个错误类型的数组;只需让数组的每个元素都是一个错误类型的代码/缩写。)如果出现错误,checker.php会重新显示include 'login.php',这将重新显示您的登录页面。

以下是诀窍:让login.php检查$error,如下所示:if isset($error) { ...如果是,请使用PHP的回显来显示错误消息。如果您愿意,可以在$error数组中转发用户ID和密码等内容。 (但在评论中注意安全方面的注意事项。)

如果未设置$error,则首次显示您的登录页面。显示它而没有错误消息。

这是一种极简主义的login.php:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Login Form</title>
<style type="text/css">
p.error {color: red;}
</style>
</head>
<body>
<?php
   if (isset($error)) {  // same message for user ID or password for security
      echo '<p class="error">Error in user ID or password; please re-enter.</p>';
   }
?>
<form method="post" action="checker.php">
<label>User ID: <input type="text" name="userid" /></label><br />
<label>Password: <input type="text" name="password" /></label><br />
User ID: <input type="submit" value="Login" /><br />
</form>
</body>
</html>

这是checker.php:

<?php
    $userid=(isset($_POST['userid']) ? $_POST['userid'] : FALSE);
    $password=(isset($_POST['password']) ? $_POST['password'] : FALSE);
    if ($userid !== 'jsnow') $error[] = 'userid';
    if ($password !== 'Ygritte') $error[] = 'password';
    if (isset($error)) {
        include 'login.php';
        exit;
    }
?>
<!DOCTYPE html>
<html>
<head>
<title>Login Success</title>
</head>
<body>
<h1>Success!</h1>
<p>You're logged in.  What do you want to do?</p>
</body>
</html>

可以在login.php页面中包含来自checker.php`的代码,但是如果你编写两个单独的页面,它会更容易看到会发生什么。在尝试组合它们之前尝试一下。

答案 3 :(得分:0)

好吧我不想要我想要的东西,但我强迫自己学习Ajax登录,它不是世界上最好的,它是我的第一个ajax登录但是对于任何人来说对答案感兴趣:

Save as login:
    <?php session_start(); $username=$ _POST[ 'username']; $password=$ _POST[ 'password']; $errors=a rray(); if ($username&&$password) { $connect=m ysql_connect( "localhost", "root", "") or die ( "Could not connect"); mysql_select_db ( "login") or die ( "Could not find database"); $query=m ysql_query( "SELECT * FROM users WHERE username ='$username'"); $numrows=m ysql_num_rows($query); if ($numrows !=0) { while ($row=mysql_fetch_assoc($query)) { $dbusername=$ row[ 'username']; $dbpassword=$ row[ 'password']; } if ($username==$dbusername&&$password==$dbpassword) { echo header( 'Location: member.php' ) ; $_SESSION[ 'username']=$dbusername; } else echo "Incorrect password"; } else die( "That user dosen't exist"); } else die( "Please enter a username and a password"); ?>

Save as scripts.js:


    function createXMLHttpRequestObject() 
    {
      var ajaxObject = false;
      if (window.XMLHttpRequest) 
      {
        ajaxObject = new XMLHttpRequest();
      } 
      else if (window.ActiveXObject) 
      {
            try 
            {
                ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");
         } 
    catch(e) 
             {
                try 
                    {
                    ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");
                } 
    catch(e) 
                    {
                        ajaxObject = false;
                 }
         }
      }
      return ajaxObject;
    }

    function grabFile(file) 
    {
      var isAjax = createXMLHttpRequestObject();
      if (isAjax) 
        {
        isAjax.onreadystatechange = function() 
          {
          getCurrentState(isAjax);
          };
        isAjax.open("GET", file, true);
        isAjax.send(null);
      }
    }

    function getCurrentState(thisFile) 
    {
      if (thisFile.readyState == 4) 
      {
        if (thisFile.status == 200 || thisFile.status == 304) 
        {
          document.getElementById('myBtn').innerHTML = 
          thisFile.responseText;
        }
      }
    }


    function ajax_post(){
        // Create our XMLHttpRequest object
        var hr = new XMLHttpRequest();
        // Create some variables we need to send to our PHP file
        var url = "login.php";
        var un = document.getElementById("username").value;
        var pw = document.getElementById("password").value;
        var vars = "username="+un+"&password="+pw;
        hr.open("POST", url, true);
        // Set content type header information for sending url encoded variables in the request
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        // Access the onreadystatechange event for the XMLHttpRequest object
        hr.onreadystatechange = function() {
            if(hr.readyState == 4 && hr.status == 200) {
                var return_data = hr.responseText;
                document.getElementById("status").innerHTML = return_data;
            }
        }
        // Send the data to PHP now... and wait for response to update the status div
        hr.send(vars); // Actually execute the request
        document.getElementById("status").innerHTML = "processing...";
    }

我没有包含它开始成为文本墙的数据库。感谢大家的意见和建议。