我一直在使用无Cookie会话解决方案战斗。当然,无cookie会话解决方案令人惊叹。我在实现它时遇到了麻烦,因为在重定向到另一个页面后我无法读取会话信息。
这是我在 testcode.php
中的测试代码<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **cannot read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
header('location: testcode.php?pagecode=' . session_id());
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
正如您所看到的,此代码不起作用。但如果我通过点击一个链接重定向到另一个页面,它运作良好。这是 testcode.php :
中的代码<?php
ini_set('session.use_trans_sid', '1');
session_start();
if (isset($_GET['pagecode'])) {
session_id($_GET['pagecode']);
print_r($_SESSION); // **able to read session information here**
exit();
}
if (isset($_SESSION['cookieconfirmed']) && $_SESSION['cookieconfirmed'] == 1) {
} else {
/** Checks if the user's browser is cookie-enabled **/
if (isset($_GET['redirected'])) { // if the page has gotten redirected
$_SESSION['cookieconfirmed'] = 1; // confirmed the cookie-disability
if (isset($_COOKIE['testcookie'])) {
header ('location: testcode.php');
} else {
echo '<a href="testcode.php?pagecode=' . session_id() . '">Click here to continue</a>';
}
} else {
setcookie('testcookie', 'OK'); //sets a test cookie.
header('location: testcode.php?redirected=1'); // redirects the page to check cookie-disability
}
exit(0);
}
?>
如何在不点击链接的情况下让它工作?
答案 0 :(得分:2)
ini_set('session.use_trans_sid', '1');
您必须在每个PHP页面上都有这个 - 您不能只在会话处理脚本中执行此操作。如果在PHP生成页面时它没有打开,它将不会将会话ID插入该页面上的表单和URL。因此,最好将它放入php.ini,或至少httpd.conf / .htaccess(作为php_value
),以使其成为所有脚本的全局选项。
答案 1 :(得分:0)
PHP function for this is :
function append_sid($link) {
if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) {
if(strpos($link, "?") === FALSE) {
return $link . "?PHPSESSID=" . session_id();
} else {
return $link . "&PHPSESSID=" . session_id();
}
} else {
return $link;
}
}
Javascript Function for this is:
function append_sid(link) {
<?php if(session_id() !== NULL && !isset($_COOKIE['PHPSESSID'])) { ?>
var session_id = '<?php echo session_id ?>';
if(link.indexOf('?') == -1) {
return link + '?PHPSESSID=' + session_id;
} else {
return link + '&PHPSESSID=' + session_id;
}
<?php } else { ?>
return link;
<?php } ?>
}
A caveat – passing session id by URL requires the session.session.use_trans_sid tio be set to 1.
php_value session.use_trans_sid = 1 in the .htaccess file. You can also try the function:
ini_set('session.use_trans_sid', '1')