douzhuican0041 2009-08-12 14:35
浏览 23
已采纳

通过Sessions改进PHP中的登录代码

Which one is the better way to handle login in PHP?

#1 PHP.net

    $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 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');

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

  • 写回答

2条回答 默认 最新

  • duangan6731 2009-08-12 15:01
    关注

    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.

    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.

    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.

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

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

报告相同问题?

悬赏问题

  • ¥20 fluent无法启动
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。