使用 mysqli 在 php 中登录和验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20025637/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:48:29  来源:igfitidea点击:

login and validation in php with mysqli

phpmysqli

提问by user3000619

Converting a mysql site to mysqli. Want to make sure this is best way to login user in and set session as the userid or username, either one. If there is a more secure way, I am open to listening. This code won't work anyway...don't know what is wrong with it. Help is appreciated.

将 mysql 站点转换为 mysqli。想要确保这是登录用户并将会话设置为用户 ID 或用户名之一的最佳方式。如果有更安全的方法,我愿意倾听。无论如何,这段代码都不起作用……不知道它有什么问题。帮助表示赞赏。

using a form, username and pwd are required. Then the connect-to-db file is called. Once connected, the admin table is queried to check for username/pwd. Nothing happens but a blank page. Here are file. Thanks.

使用表单,需要用户名和密码。然后调用connect-to-db 文件。连接后,将查询 admin 表以检查用户名/密码。什么也没有发生,只是一个空白页。这里是文件。谢谢。

form file

表格文件

<h2><br>Web Site Administration<br>
</h2> <p>Please log in below</p> 
<form   action="validate.php" method="post"> 
<b>User Name:</b> 
<br> <input type="text" size="20" name="username">
<br> <br> <b>Password:</b> 
<br><input type="password" size="20" name="password"> <br>
<br> <input type="submit" value="login"> </form>

here is the connect to db file

这是连接到数据库文件

<?php

function login();

// server info
$server = 'localhost';
$username = 'user_dbname';
$pass = 'pwd goes here';
$db = 'db and table here';

// connect to the database
$mysqli = new mysqli($server, $username, $password, $db);

//show errors (remove this line if on a live site)
mysqli_report(MYSQLI_REPORT_ERROR);

?>

and here is the validate file

这是验证文件

<?php
session_start();
include ("login.php");
login();

if(isset($_POST['submit']))
{
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$query = "SELECT username, password FROM admins WHERE username='$username' 
AND password='$password'";

$result = mysqli_query($mysqli,$query)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if( $num_row ==1 )
     {
 $_SESSION['userid']=$row['userid'];
 header("Location: admin.php");
 echo 'hi there';
 exit;
  }
  else
     {
 echo 'oops  can not do it';
  }
 }
?>

回答by Arian Faurtosh

Here is how I would do this, with a more object oriented style

这是我将如何做到这一点,更面向对象的风格

<?php

function login($username, $password)
{

    require_once '../../dbpw.php';

    $mysqli = new mysqli($dbserver, $dbusername, $dbpassword, $dbname);

    if (mysqli_connect_errno()) {
      printf("Connect failed: %s\n", mysqli_connect_error());
      exit();
    }

    $query = 'SELECT username FROM admins WHERE username=? AND password=?';

    if($stmt = $mysqli->prepare($query)){
      $stmt->bind_param('ss', $username, $password)
      $stmt->execute();
      $stmt->store_result();
      $num_row = $stmt->num_rows;
      $stmt->bind_result($username);
      $stmt->fetch();
      $stmt->close();
    }else die("Failed to prepare query");


    if( $num_row === 1 ) {
      $_SESSION['userid'] = $username;
      return true;
    }

    return false;

}

?>

This is what you have on your login page login.php:

这是您登录页面上的内容login.php

<?php

if (isset($_POST['submit'])){
    $validLogin = login($_POST['username'], $_POST['password']);

    if ($validLogin){
        header("Location: admin.php");
        exit();
     } else {
        echo 'oops can not do it';
     }

}

?>

For the admin.phppage, you'd want something different:

对于admin.php页面,您需要不同的东西:

<?php

$validLogin = login($_POST['username'], $_POST['password']);

if ($validLogin){
    echo $_SESSION['userid'] . ' is logged in';
} else {
    header("Location: login.php");
    exit();
}


?>

You will have access to $_SESSION['userid']in the admin page.

您将可以访问$_SESSION['userid']管理页面。

回答by Olu Adabonyan

Being a starter, I tried to use the method above but found out it is not CASE SENSITIVE which is important for PASSWORD validation. I have written the script below & it works perfect for password validation. The php script is:

作为初学者,我尝试使用上述方法,但发现它不区分大小写,这对于密码验证很重要。我编写了下面的脚本,它非常适合密码验证。php脚本是:

<?php
$servername = "localhost";
$username = "user";
$password = "pswd";
$dbname = "nameofmydB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
     die("Connection failed: " . mysqli_connect_error());
}
$myname = test_data($_REQUEST["myname"]);    
$mypswd = test_data($_REQUEST["mypswd"]);

function test_data($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}
$sql = "SELECT Password FROM nameofmydB WHERE Name = '$myname'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_row($result);
if ($row[0] === $mypswd){
    //Match - Case sensitive
    echo 1;
    // Set session variables
    $_SESSION["myname"] = $myname;
    $_SESSION["mypswd"] = $mypswd;
} else {
    //No Match
    echo 0;        
}
mysqli_close($conn);
?>

One can now use jquery to limit login attempt. The jquery script will have a timer etc. depending on the sensitivity of the Application. Experts may review & correct where necessary.

现在可以使用 jquery 来限制登录尝试。jquery 脚本将有一个计时器等,具体取决于应用程序的敏感度。必要时,专家可进行和纠正。

回答by bear

In your validation file, your SQL query is not selecting the useridcolumn, but only the usernameand passwordfor that user, hence setting $_SESSION['userid']will not work.

在您的验证文件中,您的 SQL 查询没有选择userid列,而只是为该用户选择usernamepassword,因此设置$_SESSION['userid']将不起作用。

Your function login()isn't written in the way functions are written in PHP, i.e the function has not been defined.

您的函数login()不是以 PHP 编写函数的方式编写的,即函数尚未定义。

What you probably want to do is something like this:

你可能想要做的是这样的:

function login($username, $password)
{

    $username = mysqli_real_escape_string($username);
    $password = mysqli_real_escape_string($password);
    $query = "SELECT * FROM admins WHERE username='$username' AND password='$password'";

   $result = mysqli_query($mysqli,$query)or die(mysqli_error());
   $num_row = mysqli_num_rows($result);

   if( $num_row == 1 )
   {
     while( $row=mysqli_fetch_array($result) ){
      $_SESSION['userid'] = $row['userid'];
     }
   } else {
      return false;
   }

  return true;
}

You'd then call the function:

然后你会调用这个函数:

// initialise database connection here. 

if (isset($_POST['submit'])){
    $validLogin = login($_POST['username'], $_POST['password']);

    if ($validLogin){
        header("Location: admin.php");
        echo 'hi there';
     } else {
        echo 'oops  can not do it';
     }

}

As example code. Note that this code is procedural and not object oriented.

作为示例代码。请注意,此代码是过程性的,而不是面向对象的。