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条)

报告相同问题?