dongliang1941 2011-03-08 18:18
浏览 48
已采纳

PHP这段代码安全吗?

I found the following code in a previous question on SO. In following code, if the username and password supplied by the user is correct, the user_id and username is stored in session to keep it logged. My question is, why there is need to keep user_id in the session? Isnt only one thing (for example, username) enough to store in session? If the remember is enabled, then a cookie is set, only with username. Now my question is, Is Only username cookie enough? Can't anyone just edit or add the cookie in the browser and log in the system?

Thanks for your replies.

<?
public function login($username, $pass, $remember) {
    // check username and password with db
        $result = $conn->query("select * from login where
                            username='".$username."' and
                           password=sha1('".$pass."')");
        if (!$result) {
            throw new depException('Incorrect username and password combination. Please try again.');
        } 

       if ($result->num_rows>0) {
            $row = $result->fetch_assoc();
            $_SESSION['user_id'] = $row[user_id];
            $_SESSION['username'] = $username;

           // start rememberMe
            $cookie_name = 'db_auth';
            $cookie_time = (3600 * 24 * 30);*/ // 30 days

            // check to see if user checked box
            if ($remember) {
            setcookie ($cookie_name, 'username='.$username, time()+$cookie_time);
            }

            // If all goes well redirect user to their homepage.
            header('Location: http://localhost/v6/home/index.php'); 
            } else {
           throw new depException('Could not log you in.');
            }
    }

?>
  • 写回答

5条回答 默认 最新

  • dongwen5870 2011-03-08 18:20
    关注

    THIS CODE IS NOT SECURE! (Sorry for the caps, but its for the emphasis). The SQL statement is susceptible to SQL injection. Also storing the username in the cookie is a bad idea because anyone can forge the cookie to gain authentication.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)