【发布时间】:2017-05-21 06:42:25
【问题描述】:
这个问题可能有点愚蠢,但我只是从会话开始我的冒险 - 以前不需要使用它们。在主页上我有一个正确存储所有变量的会话,没问题。
当我转到同一域下的子页面并尝试从会话中调用变量时,我只会得到空字段。我试着做 print_r($_REQUEST);在子页面上,它会打印出以下内容:
Array ( [wp-settings-1] => libraryContent=browse&editor=html [wp-settings-time-1] => 1478015951 [PHPSESSID] => 0744bf21ab3712e4735e07d926433aa3 [sec_session_id] => 60e56049f51c76e9ec4932c6702e7b72 )
与主页上的输出相匹配。我知道我应该做一个 session_start();但是当我将它包含在我的代码中时,我收到以下错误:
Notice: A session had already been started - ignoring session_start()
我知道变量没有被传递的原因是因为当我这样做时
if(isset($_SESSION["user_id"])){
$user_id = $_SESSION["user_id"];
}
echo "User id: " .$_SESSION["user_id"];
我只会得到
User id:
每当我尝试调用该变量时,我都会收到未设置的错误。
有没有我遗漏的步骤?
设置会话变量:
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$sessions['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
if (!$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')")) {
header("Location: ../error.php?err=Database error: login_attempts");
exit();
}
return false;
}
}
} else {
// No user exists.
return false;
以及启动安全会话的功能:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
if (ini_set('session.use_only_cookies', 1) === FALSE) {
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
【问题讨论】:
-
您在哪里将 user_id 设置为会话?如果是 wordpress 使用全局 $session;print_r($sessions);它将打印您的会话变量。将 user_id 设置为会话---$sessions['user_id']='your user id';您可以在应用程序的任何位置访问
-
不是我在登录平台的时候在php session中设置user_id,跟wordpress没有关系 $_SESSION['user_id'] = $user_id;