Problem with session_set_save_handler

2

I'm using session_set_save_handler to write the session to MySQL, but an error has been tormenting me.

When I log in to IE with a user, then I close the browser without giving logout and I enter Chrome, I'm already logged in with the IE user. That is, it is automatically logging me in with another user's session.

Here's my function:

 <?php

GLOBAL $mysqli_link;

function _open($save_path, $session_name) {
    return true;
}

function _close() {
    return true;
}

function _read($id) {
    GLOBAL $mysqli_link;

    $id = hash('sha512', $id);

    $stmt = $mysqli_link->prepare("SELECT data FROM session WHERE  id = ? limit 1");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $num = $result->num_rows;

    if ($num>0) {
        $record = $result->fetch_assoc();
        return $record['data'];
    }
    else{
        return '';
    }
}

function _write($id, $data) {
    GLOBAL $mysqli_link;

    //echo session_id();

    $id = hash('sha512', $id);

    $access = time();

    if($data!=""){
        $stmt = $mysqli_link->prepare("REPLACE INTO session VALUES (?,?,?)");
        $stmt->bind_param('sss', $id, $access, $data);
        $stmt->execute();
    }

    return true;
}

function _destroy($id) {
    GLOBAL $mysqli_link;

    $id = hash('sha512', $id);

    $stmt = $mysqli_link->prepare("DELETE FROM session WHERE id = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
}

function _clean($max) {
    GLOBAL $mysqli_link;
    $CurrentTime = time();

    //$old = time() - $max;
    //$stmt = $mysqli_link->prepare("DELETE FROM session WHERE access < ?");

    $stmt = $mysqli_link->prepare("DELETE FROM session WHERE access + ? < ?");
    $stmt->bind_param('ss', $max, $CurrentTime);
    $stmt->execute();
}

session_set_save_handler('_open','_close','_read','_write','_destroy','_clean');
register_shutdown_function('session_write_close');



?>

---------------------------------------- > EDITED

in the index.php page I have this:

session_start();

if(isset($_SESSION["user"])){
 $user = $_SESSION["user"];
 header("Location:welcome.php");
 die();
}

The intention here is to check if the person is logged in, if so, send to welcome.php page.

and no welcome do I have this to check if the user is actually logged in to continue on the page:

session_start();

if(empty($_SESSION["id"]) || empty($_SESSION["user"]))
{
    header("Location:login.php");
    die();
}
    
asked by anonymous 05.05.2015 / 00:26

1 answer

0

I can argue and say that the problem is Replace Into used in your code.

Change to:

if (empty($data)) {
    $stmt = $mysqli_link->prepare("INSERT INTO session VALUES (?,?,?)");
    $stmt->bind_param('sss', $id, $access, $data);
    $stmt->execute();
}

That was just a quick example. But the ideal would be to check if there is any row in the table with this id. If it exists, you upgrade; if not, you enter.

    
18.08.2015 / 20:53