【发布时间】:2017-08-24 18:49:06
【问题描述】:
我正在尝试弄清楚如何使会话安全。我做了很多研究并找到了我想要的东西,但是安全会话无法正常工作,并且该网站没有说明如何修复它。
当你查看代码时,
测试 1 将失败
但是运行的时候,需要通过。
同样,当您拉取 $_SESSION 变量时,Test1 中也没有任何内容。
我注意到的是,如果我将 $_SESSION 放在加密后它接受它。
函数来自以下站点:http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
$_SESSION['user_id'] = 'test';
$_SESSION['username'] = 'john';
$_SESSION['login_string'] = '1234';
echo 'Session Set<br>';
sec_session_start();
// Testing $session pass or fail.
echo 'test1<br>';
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string'])){
echo 'test: Pass';
} else {
echo 'test: failed';
}
echo '<br>';
echo 'test2<br>';
$_SESSION['user_id'] = 'test';
$_SESSION['username'] = 'john';
$_SESSION['login_string'] = '1234';
echo 'Session Set<br>';
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string'])){
echo 'test: Pass';
} else {
echo 'test: failed';
}
// Function from following site: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
/*Sets the session name.
*This must come before session_set_cookie_params due to an undocumented bug/feature in PHP.
*/
session_name($session_name);
$secure = true;
// 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);
session_start(); // Start the PHP session
session_regenerate_id(true); // regenerated the session, delete the old one.
}
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
【问题讨论】:
-
您在使用
session_start()初始化变量之前尝试使用$_SESSION变量 -
@Ibu 虽然在不初始化会话的情况下“使用它”并没有错,但它确实会擦除 $_SESSION 的现有内容。
-
用$_SESSION在网页之间穿梭,在调用函数sec_session_start()之前最好把$_SESSION变量拉出来吗?