PHP Session问题

时间:2010-12-23 07:32:39

标签: php

好的,我的代码应该使用$ _GET ['pid']获取页面ID并检查它是否等于$ _SESSION ['page']。如果保留$ _SESSION ['page'],如果没有销毁$ _SESSION ['page']。

但由于某种原因,当我使用include()从另一个页面调用该函数时,$ _SESSION ['page']在重新加载时与另一个页面具有不同的值?是什么导致了这个问题,我该如何解决?

这是我未设置的$ _SESSION ['page']代码。

<?php
ob_start(); 
session_start();

if(isset($_GET['pid']) && is_numeric($_GET['pid'])) {
    if(isset($_SESSION['page']) && $_SESSION['page'] !== $_GET['pid']){
        unset($_SESSION['page']);
    }

    $page = mysqli_real_escape_string($mysqli, htmlentities(strip_tags($_GET['pid'])));
    $_SESSION['page'] = $page;
}

ob_flush();
?>

我从另一个脚本中调用此函数

<?php
ob_start(); 
session_start();
function getRatingText(){
    $dbc = mysqli_connect("localhost", "db", "pass", "members");
    $sql1 = "SELECT COUNT(ab_g.u_ab_id) FROM ab_g INNER JOIN u ON ab_g.user_id = u.user_id WHERE u_ab_id = '" . $_SESSION['page'] . "' AND u.active IS NULL AND u.deletion = 0";
    $result = mysqli_query($dbc,$sql1);

    if (!mysqli_query($dbc, $sql1)) {
            trigger_error(mysqli_error($dbc));
            return;
    } else {
        while($row = mysqli_fetch_array($result)) {
            $tr[] = $row[0];
        }
    }

    if(isset($tr) && count($tr) != 0){ $rat = array_sum($tr); }

    $sql2 = "SELECT g.rate_points FROM g INNER JOIN ab_g ON g.id = ab_g.rate_id INNER JOIN u ON ab_g.user_id = u.user_id WHERE ab_g.u_ab_id = '" . $_SESSION['page'] . "' AND u.active IS NULL AND u.deletion = 0";
    $result = mysqli_query($dbc, $sql2);

    if(!mysqli_query($dbc, $sql2)) {
        trigger_error(mysqli_error($dbc));
        return;
    } else {
        while($row = mysqli_fetch_array($result)) {
            $trp[] = $row[0];
        }
    }

    if(isset($trp) && count($trp) != 0){ $tot = array_sum($trp); }

    if (!empty($tot) && !empty($rat)){
        $avg = round($tot / $rat, 1);
        $percent = round(($avg / 5) * 100, 1);
        $votes = $rat;
        if($rat == 1){
            echo $avg . "/5  (" . $votes . " rating casted)";
        } else {
            echo $avg . "/5  (" . $votes . " casted)";
        }

        if($avg <= 5){ $rate = '5 star'; }

        if($avg <= 4){ $rate = '4 star'; }

        if($avg <= 3){ $rate = '3 star'; }

        if($avg <= 2){ $rate = '2 star'; }

        if($avg <= 1){ $rate = '1 star'; } 

        echo $rate;

    } else {
        echo 'not rating';
    }   
  return TRUE;
}

ob_flush();
?>



我通过将 session_write_close(); 放在底部的函数脚本中解决了这个问题。在ob_flush()之前。

2 个答案:

答案 0 :(得分:1)

如果pid无效,请尝试执行unset($_SESSION['page']);

if(isset($_GET['pid']) && is_numeric($_GET['pid'])) {
    ....
} else {
    unset($_SESSION['page']);
}

答案 1 :(得分:0)

只有在您遇到http标头问题时才能使用

ob_start() and ob_flush()