gpt4 book ai didi

php - 存储 session 变量时出现问题

转载 作者:行者123 更新时间:2023-11-29 08:42:50 25 4
gpt4 key购买 nike

我有一个登录脚本,当前存储 2 个变量:一个有效变量和一个用户名变量。我现在尝试添加名称变量,因此我更改了 MySQL 查询以从数据库获取名称,并尝试将名称存储在 session 变量中,但由于某种原因它只是不存储它。也许最好只是向您展示该脚本,我只学习了 2 个月的 PHP,所以我非常感谢您的帮助。

<?php
ob_start(); // Start output buffering

session_start(); //must call session_start before using any $_SESSION variables3
$_SESSION['username'] = $username;

function validateUser($username)
{

session_regenerate_id (); //this is a security measure
$_SESSION['valid'] = 1;
$_SESSION['username'] = $username;
$_SESSION['name'] = $userData['name'];
}

$username = isset($_POST['username'])?$_POST['username']:'';
$password = isset($_POST['password'])?$_POST['password']:'';

//connect to the database here

$hostname_Takeaway = "localhost";
$database_Takeaway = "diningtime";
$username_Takeaway = "root";
$password_Takeaway = "root";
$Takeaway = mysql_pconnect($hostname_Takeaway, $username_Takeaway, $password_Takeaway) or trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_Takeaway, $Takeaway);

$username = mysql_real_escape_string($username);

$query = "SELECT name, password, salt FROM admin_users WHERE username = '$username';";

$result = mysql_query($query) or die(mysql_error());

if(mysql_num_rows($result) < 1) //no such user exists
{
header('Location: http://localhost/diningtime/admin-home.php?login=fail');

die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password


{
header('Location: http://localhost/diningtime/admin-home.php?login=fail');

die();
}
else
{

validateUser($username); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: http://localhost/diningtime/main');
die();




//redirect to another page or display "login success" message


?>

最佳答案

您的 validateUser() 函数作用域内没有 $userData 变量,因此您将 NULL 分配给 $_SESSION['name']。

要么使 $userData 成为全局变量,以便它在函数范围内可见,要么将其作为参数传递:

function validateUser($user, $userData) {
^^^^^^^^^-- pass as arg
global $userData;
^^^^^^^^^^^^^^^^^--- bring var in-scope
...
$_SESSION['name'] = $GLOBALS['userData']['name'];
^^^^^^^^^^^^^^^^^^^^^^^^^^^^--- refer to global scope
}

这 3 个选项中的任何一个都可以解决问题(只是不要同时执行所有三个选项)

关于php - 存储 session 变量时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13296664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com