2

I work in a website and we need to cluster server to have more than 1 computer handling with traffic. so I need to convert php session (file session) to a db for this cluster work.

I have a simple login file: check if post user == password, if num rows == 1:

$_SESSION['user']=$_POST['user'];

my problem starts here, how can I write this USER in my database using session_set_save_handler? what I need to change get _write work?

public function _write($id){
  // Create time stamp
  $data = time();

  // Set query  
  $this->db->query('INSERT INTO sessions (id,user,data) VALUES (:id, :user, :data)');

  // Bind data
  $this->db->bind(':id', $id);
  $this->db->bind(':user', $user);  //how can i get login user?
  $this->db->bind(':data', $data);

  // Attempt Execution
  // If successful
  if($this->db->execute()){
    // Return True
    return true;
  }

  // Return False
  return false;
}

DB

CREATE TABLE IF NOT EXISTS `sessions` (
  `id` varchar(32) NOT NULL,
  `user` varchar(20),
  `data` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Gabriela Dias
  • 349
  • 2
  • 12

2 Answers2

0

The write function of the session_set_save_handler, accepts two arguments:

function write(string $sessionId, string $data)
{
    //$data = serialized presentation of your whole session, including 'user'
    ...
}

See What kind of serialization uses PHP function session_set_save_handler's write function? For more info

Community
  • 1
  • 1
sanderbee
  • 694
  • 7
  • 24
0

Firstly, your _write function misses second argument, in this case $user:

function _write($id,$user)

that's where your data (contents of $_SESSION array) is located. The name $user is confusing, it is just any data that is contained in $_SESSION array, so it would be better to use for example $value name.

Also as id in your session table should be unique, it might not succeed if there is already such session. So in that case you update it with expiration time:

if($this->db->execute()){
    return true;
}else{
    $this->db->query('UPDATE sessions SET user=:user, data:data WHERE id=$id');

    $this->db->bind(':access', $access);  
    $this->db->bind(':data', $data);

    $this->db->execute();
}

As to the time, it should be expiration time, you better change it to:

$data = time()+ini_get("session.gc_maxlifetime");

n-dru
  • 9,285
  • 2
  • 29
  • 42
  • oh, so $sessionId has the id from session that is in user browser and my db? and data all other $_SESSION['SOMETHING']? – Gabriela Dias Apr 17 '15 at 14:52
  • yes, this table should have unique id of session, expiration time and value of all `$_SESSION` serialized. – n-dru Apr 17 '15 at 14:55