dprh34164 2013-06-13 15:05
浏览 29
已采纳

使用会话使登录脚本安全

I am currently busy with my own login script that is simple but also safe enough to fit my goal. It uses MySQL to save the usernames and passwords. Now I came to the point of using sessions to be able to check whether a user is logged in, just like it can be found in many tutorials. So far I came up to this, but I'm just not sure whether this is a proper/safe way to do this.

<?php

$db = new PDO('mysql:host=HOST;dbname=DATABASE;charset=UTF-8', 
              'USERNAME', 
              'PASSWORD',
              array(PDO::ATTR_EMULATE_PREPARES => false,
              PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

if(isset($_POST['username']) && isset($_POST['password'])){
  $select = $db->prepare("SELECT id, username FROM vwo5_users WHERE username=:username AND password=:password");
  $select->execute(array(':username' => $_POST['username'], ':password' => $_POST['password']));
  $amount = $select->rowCount();
  $result = $select->fetch(PDO::FETCH_ASSOC);
  $user_id = $result['id'];
  $user_name = $result['username'];


  if($amount >= 1){
    session_start();
    $_SESSION['user_id'] = $user_id;
    $_SESSION['user_name'] = $user_name;
    echo 'Logged in';
  }
  else{
    echo 'Wrong login data';
  }  
}
else{
    header('Location: dbtestform.php');
}

?>

I would then check at a secured page whether the id and username from the session go together in the database as well, but I can't put my finger on the point of this being safe or not. I know it's being described all over the internet, but no source I found made it more clear to me.

  • 写回答

1条回答 默认 最新

  • dongyuan2652 2013-06-13 15:32
    关注

    I'm just not sure whether this is a proper/safe way to do this.

    Looks fine, but it doesn't appear you're hashing your passwords which you should definitely do. Look into BCrypt.

    I don't believe people typically store both the user id and username in the session, just store one or the other and you can query whatever other information you need when a new request is made.

    Other than the hashing it looks perfectly fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算