通过Sessions改进PHP中的登录代码 [英] To improve login code in PHP by Sessions

查看:50
本文介绍了通过Sessions改进PHP中的登录代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方法是处理PHP中登录的更好方法?

    $email = $_POST['email'];
    $password = $_POST['password'];
    if($user->connection($email,$password)){ // user logging validation
        session_start();     //start the session
        $_SESSION['user_logged'] = true;  // user logged in
        header('location : control_panel.php');  // go to control panel
    }
    else {  // go back to logging page
        header('location : logging.php?' . $user->error_string);
    }

#2我 Paul Dixon的改进和Sebasgo的改进

#2 Me after Paul Dixon's improvements and Sebasgo's improvements

 if (isset($_REQUEST['email'])) {
     $result = pg_prepare($dbconn, "query22", "SELECT passhash_md5 FROM users
         WHERE email=$1;");                                             
     $passhash_md5 = pg_execute($dbconn, "query22", array($_REQUEST['email']));                 

     session_start(); 
     $_SESSION['logged_in'] = false;                                                                                                           
     if ($passhash_md5 == $_REQUEST['passhash_md5']) {                                            
         $_SESSION['logged_in'] = true;                                                                   

 }
 header('Location: index.php');

代码2具有$_REQUEST命令,因为我仍在努力使其正常工作.

The code #2 has $_REQUEST commands because I am still trying to get it work.

推荐答案

您不应该尝试自己管理会话ID.类似于您建议的方案(将每个新会话的会话ID增加一个)的简单方案包含一个严重的安全问题:具有新生成的会话ID的用户可以通过尝试尝试使用比其自身稍小的ID来琐​​碎地猜测其他有效的会话ID.因此,两个人很容易获得别人的会话.

You shouldn't try to manage the session ids yourself. A simple scheme like the one you propose (incrementing the session id by one for every new session) contains a serious security issue: A user with freshly generated session id can trivially guess other valid session ids by trying ids slightly smaller than its own. Thus it is very easy two acquire someone else's session.

如果让PHP为您管理新会话ID的生成,PHP将使用伪随机生成器来创建新ID,这对于潜在的攻击者来说很难猜到.这样可以有效地防止上述攻击情形.

If you let PHP manage the generation of new session ids for you, PHP uses a pseudo random generator to create the new ids, which will be hard to guess for a potential attacker. This prevents the above outlined attack scenario effectively.

此外,在调用session_start()之前,您几乎永远不会访问$_SESSION,因为在此之前,会话数组将始终为空.因此,您对empty($_SESSION['SID'])的测试将始终提高false.

Additionally, you will virtually never want to access $_SESSION before calling session_start() because before the session array will be always empty. Therefore your test of empty($_SESSION['SID']) will always raise false.

底线:我强烈建议您坚持使用类似PHP.net这样的简单登录管理方法.

Bottom line: I strongly recommend you to stick to the simple way of managing login like PHP.net does it.

这篇关于通过Sessions改进PHP中的登录代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆