Session Destroyed on page refresh

1.3k views Asked by At

i have php file which works fine on the first load but session is destroyed after refresh page. On refresh php page i get Warning: session_regenerate_id(): Session object destruction failed

<?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>

in member.php i also start session

<?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);
?>

Questions:

  1. Why session value is not passed in member.php after refresh page?

  2. What are the best approach to pass the Session value into member.php?

2

There are 2 answers

3
Sougata Bose On BEST ANSWER

There is a syntactical error. Should be -

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

isset is a function. It should be called by isset() not isset[].

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

There is error in your code In the third line you have used square brace[ ] with isset,instead of round brace()