会话在页面刷新时被破坏

时间:2015-06-09 05:11:02

标签: php ajax session

我有php文件在第一次加载时工作正常,但会话在刷新页面后被销毁。在刷新php页面上我收到警告:session_regenerate_id():会话对象销毁失败

<?php
    /** functions.php **/
    function startSession() {
        $session_name = 'sec_session_id';   // Set a custom session name
        session_name($session_name);
        session_start();                    // Start the PHP session 
        session_regenerate_id(true);        // regenerated the session
    }
?>

<!-- controller.js -->
function LoadFriend() {
        var listFriend = $('#list_member_friend');
        var UrlToPass = 'action=load';
        listFriend.html('loading..');
        $.ajax({
            url : 'ajax.php',
            type : 'POST',
            data : UrlToPass,
            success: function(responseText) {
                listFriend.html(responseText);
            }
        });
    }
loadFriend();
<!-- end controller.js -->

<?php
    /** ajax.php **/
    $action = $_GET['action']
    switch($action) {
       case "load": 
           /** PRINT LIST FRIEND **/
       ...
    }
?>

<?php
    /** index.php **/
    include('functions.php');
    startSession();
    $userid = 'HENRY';
    if(!isset($_SESSION['user_id'])) {
        $_SESSION['user_id'] = $userid;
    } 
?>
<html>
   <head>
       <title>Load List</title>
       <script src="controller.js" type="text/javascript"/>
   </head>
   <body>
       <div id="list_container">
           <div id="list_member_friend" class="list_member_friend">
           <!-- this is where it generates session error -->
           <!-- load list of members friend with ajax script controller.js from member.php -->
           </div>
       </div>
   </body>
</html>
在member.php中

我也开始会议

<?php 
    /** member.php **/
    include('functions.php');
    startSession()
    $db = new MySQLi('localhost','root','abcdefg','social');
    $query = "SELECT fid, fname, fage, fgender FROM memberFriends";
    $query .= " WHERE memberid = '" . $_SESSION['user_id'] . "'"; <!-- this is the problem -->
    $db->prepareQuery($query);
    $db->execute();
    ..... (Load List);
?>

问题:

  1. 为什么会在刷新页面后的member.php中传递会话值?

  2. 将Session值传递给的最佳方法是什么?     member.php?

2 个答案:

答案 0 :(得分:3)

有句法error。应该是 -

if(!isset($_SESSION['userid'])) {

isset是一个功能。它应该由isset()而非isset[]调用。

答案 1 :(得分:2)

<?php
    session_start();
    $userid = 'HENRY';
    if(!isset($_SESSION['user_id'])) {
        $_SESSION['user_id'] = $userid;
    } 
?>

代码中有错误在第三行中,您使用了带有isset的方括号[],而不是使用圆括号()