簡體   English   中英

如何使用會話功能傳遞用戶名

[英]How to pass the username by using session function

<?php
session_start();
error_reporting(E_ALL ^ E_DEPRECATED);
$host = "localhost";
$user = "root";
$pass = "";
$db = "testing";
mysql_connect($host, $user, $pass);
mysql_select_db($db);
if (isset($_POST['loginID'])) {
    $loginID = $_POST['loginID'];
    $password = $_POST['password'];
    $sql = "SELECT * FROM user WHERE loginID='".$loginID."' AND password='".$password."' LIMIT 1";
    $res = mysql_query($sql);
    if (mysql_num_rows($res) == 1) {
        header("Location:homepage.php");
        $_SESSION['loginID'] = $loginID;
    } else {
        header("Location:login.php");die;
    }
}
?>

我想在會話中傳遞用戶名,以在homepage.php顯示用戶名,但是當我嘗試這樣做時卻不起作用。 有什么問題,我該如何運作?

更改此:

if(mysql_num_rows($res)==1)
{
header("Location:homepage.php");
$_SESSION['loginID']=$loginID;
}

對此:

if(mysql_num_rows($res)==1)
{
$_SESSION['loginID']=$loginID;
header("Location:homepage.php");
}

會話值應先存儲,然后重定向到另一個頁面。 嘗試以下操作:if(mysql_num_rows($ res)== 1){$ _SESSION ['loginID'] = $ loginID; 標題( “位置:homepage.php”); }

您需要從結果集中獲取一行,並將該行中的信息用於會話變量:

$res = mysql_query($sql);
if ($row = mysql_fetch_assoc($res)) {
    $_SESSION['loginID'] = $loginID;
    $_SESSION['name'] = $row['username'];    // or whatever the column is called where the username is stored
    header("Location:homepage.php");
    exit();
} else {
    header("Location:login.php");die;
}

除此之外,還有一些評論:

  • 您應該使用准備好的語句切換到PDO或mysqli。 mysql_*函數已被棄用,您現在遇到了sql注入問題;
  • 您永遠不應存儲純文本(或加密的)密碼。 密碼應加鹽和散列, 有關PHP密碼 ,請參閱安全散列和鹽

暫無
暫無

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

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