簡體   English   中英

使用會話的正確方法?

[英]The correct way to use sessions?

我對 PHP 相當陌生。

我已經為我的網站制作了一個登錄系統,我想知道我是否以正確的方式處理這個問題。 在處理登錄請求的login.php ,我創建了會話變量以在我的站點上使用。 我想知道這是否是存儲用戶數據的最有效/最安全的方式。

這種方法對我來說似乎很有效。 但是假設我需要另一個表中不包括在我的用戶表中的數據。 我將如何獲取該信息並將其存儲到會話中? 由於瀏覽器擁有所有這些信息,這是否會使我的用戶容易受到攻擊? 或者我對會話的理解完全錯誤。

<?php
/* User login process, checks if user exists and password is correct */

// Escape email to protect against SQL injections
$email = $mysqli->escape_string($_POST['email']);
$result = $mysqli->query("SELECT * FROM users WHERE email='$email'");

if ($result->num_rows == 0) { // User doesn't exist
    $_SESSION['message'] = "User with that email doesn't exist!";
    header("location: error.php");
} else { // User exists
    $user = $result->fetch_assoc();

    if ( password_verify($_POST['password'], $user['password']) ) {

        $_SESSION['email'] = $user['email'];
        $_SESSION['user_name'] = $user['user_name'];
        $_SESSION['active'] = $user['active'];
        $_SESSION['paid'] = $user['paid'];
        $_SESSION['bitaddress'] = $user['bitaddress'];
        $_SESSION['id'] = $user['id'];
        $_SESSION['firstName'] = $user['firstName'];
        $_SESSION['lastName'] = $user['lastName'];

        // This is how we'll know the user is logged in
        $_SESSION['logged_in'] = true;

        header("location: checksum.php");
    } else {
        $_SESSION['message'] = "You have entered wrong password, try again!";
        header("location: error.php");
    }
}

您應該為會話創建一個方法,例如:

function session_start(){
  session_start()
}
function session_create($key,$value){
  return   $_SESSION[$key] = $value;
}
function session_destroy(){
  session_destroy();
}

只要使用不同的鍵,就可以存儲來自多個表(或任何其他值)的數據。

會話存儲在服務器端,因此您的瀏覽器沒有此信息。 但是仍然存在漏洞,請參閱會話劫持https://www.owasp.org/index.php/Session_hijacking_attack

通常,您會很好地使用會話。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM