【问题标题】:Fetching data from mySql database for php user session从 mySql 数据库中获取 php 用户会话的数据
【发布时间】:2017-12-27 07:46:06
【问题描述】:

我对 PHP 和 mySQL 比较陌生,我正在尝试使用 mySQL 数据库中的字段创建用户会话。

我设置它的方式意味着我通过对照数据库检查输入登录表单(用户名和密码)的两个字段来获得会话,但我无法从数据库中检索任何其他数据并且将其添加到会话中。

如何从数据库中检索其他数据并将其添加到新会话中?

<?php
require('db.php');
session_start();

// If form submitted, insert values into the database.
if (isset($_POST['username'])){
    // removes backslashes
    $username = stripslashes($_REQUEST['username']);
    //escapes special characters in a string
    $username = mysqli_real_escape_string($con,$username);
    $password = stripslashes($_REQUEST['password']);
    $password = mysqli_real_escape_string($con,$password);
    //Checking is user existing in the database or not
    $query = "SELECT * FROM `users` WHERE username='$username' and password='".md5($password)."'";
    $result = mysqli_query($con,$query) or die(mysql_error());
    $rows = mysqli_num_rows($result);
    if($rows==1){
        //This one works
        $_SESSION['username'] = $username;

        //This one doesn't
        $_SESSION['email'] = $rows ['email'];

        // Redirect user to index.php 
        header("Location: index.php");
    }else{
        echo "<div class='form'>
        <p>Username/password is incorrect.</p>
        <br/>Click here to <a href='login.php'>Login</a></div>";
    }
}else{
}
?>

【问题讨论】:

  • 仅使用 MD5 之类的哈希函数是不够的,仅添加盐对提高安全性无济于事。而是使用随机盐在 HMAC 上迭代大约 100 毫秒,然后将盐与哈希一起保存。使用PBKDF2Rfc2898DeriveBytespassword_hashBcryptpasslib.hash 等函数或类似函数。关键是让攻击者花费大量时间通过蛮力寻找密码。

标签: php mysql


【解决方案1】:

$rows 是计数器变量(具有记录数),这就是为什么不工作的原因。

像下面这样:-

....previous code as it is
$result = mysqli_query($con,$query) or die(mysql_error());
$row = mysqli_fetch_assoc($result); //fetch record
$rows = mysqli_num_rows($result);
if($rows==1){
        $_SESSION['email'] = $row['email'];
        header("Location: index.php");
    }...rest code as it is

注意:-

1.不要使用md5密码加密,使用password hashing技术。

2.使用mysqli_* 中的prepared statements 来防止您的代码SQL 注入

【讨论】:

  • 谢谢!这对我有用。我会研究密码加密和准备好的语句,谢谢你的建议!
  • @PhillipMitchell 很高兴帮助你:)
猜你喜欢
  • 2016-06-15
  • 2016-07-10
  • 2016-03-22
  • 1970-01-01
  • 2021-05-23
  • 2013-08-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
相关资源
最近更新 更多