检查与服务器变量的会话

时间:2011-04-27 06:31:56

标签: php session

我一直试图通过检查以下代码(部分)来保护我的页面:

if (($_SERVER['REMOTE_ADDR'] != $_SESSION['USER_IP']) || !isset($_SESSION['SERVER_GENERATED_SID']))
{
    session_destroy();
}

$_SESSION['SERVER_GENERATED_SID'] = true;
$_SESSION['USER_IP'] = $_SERVER['REMOTE_ADDR'];

由于某种原因,它每次都会杀死会话。

这是我的索引页面:

<?php
require('includes/sessions.php');
require('includes/language.php');

$page_name = "Anchor & Steel Constructions";

require('includes/header.php');
?>

<div id="page">
        <div>
            <div id="content">
                <?php

                if(!isset($_SESSION['user_id']) || !in_array($_SESSION['user_type'], $user_types))
                {
                    include('user_login.php');
                }

                ?>
            </div>
        </div>
        <div style="clear: both;">&nbsp;</div>
</div>

我的登录代码,其中变量被添加到会话中: $ _SESSION ['user_ip'] = $ _SERVER ['REMOTE_ADDR'];

$_SESSION['user_id'] = $row['user_id'];
                $_SESSION['user_user'] = $row['user'];
                $_SESSION['user_name'] = $row['naam'];
                $_SESSION['user_mail'] = $row['email'];
                $_SESSION['user_lang'] = $row['language'];

会话:

<?php
// gebruik een andere naam voor de sessie dan de standaard php naam
session_name('what_ever');

// start session
if(!session_start())
{
    exit("Er kan geen sessie worden gestart");
}

// generate nieuwe sessie id
session_regenerate_id();

// set timeout period in seconds
if($_SESSION['user_type'] != 'beheerder')
{
    $inactive = 180;
}
else
{
    $inactive = 28800;
}

// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
        { session_destroy(); header("Location: user_logout.php"); }
}
$_SESSION['timeout'] = time();

$user_types = array('beheerder', 'kantoor', 'werkplaats', 'administratie');

// controleer of de user gebruikt maakt van dezelfde user agent als bij voorgaande request en accepteer alleen door server gegenereerde SID's
if (($_SERVER['REMOTE_ADDR'] != $_SESSION['user_ip']) || !isset($_SESSION['SERVER_GENERATED_SID']))
{
    session_destroy();
}

// sla variabelen op
$_SESSION['SERVER_GENERATED_SID'] = true;
$_SESSION['user_ip'] = $_SERVER['remote_addr'];

?>

2 个答案:

答案 0 :(得分:1)

检查时是否设置了$_SESSION['SERVER_GENERATED_SID']

从对这个答案的评论来看,
如何将$_SESSION['user_ip'] = $_SERVER['remote_addr']更改为$_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'];

答案 1 :(得分:1)

确保您在php / html代码的开头编写了代码session_start();

示例

<?php 
session_start();

?>
<html><head></head><body>hi friend</body></html>