【问题标题】:PHP and HTML how can i load in a new filePHP和HTML如何加载新文件
【发布时间】:2017-01-14 08:06:41
【问题描述】:

我在 PHP 中创建了一个登录页面,用户在其中输入他们的详细信息,然后将它们发布到另一个 PHP 文件,然后检查用户输入的用户名并查看它是否在 MySQL 帐户表中注册,如果是,则检查密码,如果匹配,我希望它打开个人资料页面,如果不是,我希望它返回登录页面。如何让 PHP 代码加载到要在屏幕上显示的新 html/php 文件中。到目前为止,这是我的 PHP 代码:

<html>

<?php
include_once "mysql_connect.php";

$usersName = $_POST['usersname'];
$passWord = $_POST['passsword'];

$result = mysql_query("SELECT * FROM allaccounts");
$num_rows = mysql_num_rows($result);

$username = "";
$password = "";

for ($i = 1; $i <= $num_rows; $i++) {
    $currentname = mysql_query("SELECT * FROM allaccounts WHERE id=$i");

    while ($row = mysql_fetch_array($currentname)) {
        $username = $row[0];
        $password = $row[1];
    }
    if (($username === $usersName) && ($password === $passWord)) {
        echo "We got you";
        break;
    } else {
        echo "nothing";
    }
}
?>
</html>

【问题讨论】:

  • 重定向到登录页面或个人资料页面:stackoverflow.com/questions/7467330/…
  • 为什么要在每个 DB 行上运行查询,然后在 PHP 中比较匹配? $result = mysql_query("SELECT password FROM allaccounts where username = ?"); 你应该更新你的驱动程序,这样你也可以使用参数化查询;并且密码应该是散列的。
  • 顺便说一句,编写的代码存在两个严重问题。首先是 mysql_* 函数在 PHP 5 中被弃用并在 PHP 7 中被删除;强烈建议您使用 PDO (quick tutorial)。其次,您似乎正在将数据库中的密码与输入密码进行比较。看起来您将密码以明文形式存储在密码中,这绝对是一种糟糕的安全做法。而是使用password_hash 函数及其相关方法。

标签: php html mysql


【解决方案1】:

使用 header() 函数。这将重定向到指定的页面。

if (($username === $usersName) && ($password === $passWord)) {
           header("Location: profile.php");
    } else {
           header("Location: fail.php");
    }

另外——去掉顶部的&lt;html&gt;。它没有用,意味着标头已经发送。

【讨论】:

  • 别忘了exit 否则(不必要的)循环将继续进行。
  • 这是正确的函数,但实际上你会在上面的代码中得到一个错误(提示:已经有任何东西输出到页面了吗?)
  • 在任何其他示例中,是的!但是当我们此时重定向页面时 - 它充当退出。 @chris85
  • @ChrisForrence,怎么样?除了我当然使用了示例文件名这一事实。
  • 页面继续执行,但页眉被扔给浏览器。 php.net/manual/en/function.header.php另见stackoverflow.com/questions/2747791/…
【解决方案2】:

您可以使用ajax 调用来施展魔法。可以使用内联或外部脚本进行 ajax 调用。

这有助于您通过降低加载另一个页面的复杂性来在同一窗口/页面中显示错误消息。

它看起来像这样......

            // add the code inside a function which should be 
            // invoked on submitting the login details

              $.ajax({

                    type    : "POST",
                    url     : "your_login_check.php",
                    data    : anyVariable,
                    dataType: "HTML",

                    success : function(data){


                        if( data === "We got you"){

                           // Display an error message in a div or simply an alert
                        }

                        else if( data === "nothing"){
                           // Redirect to a specific page

                           window.location = "//Your_another_page.php//";
                        }
              )};

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多