Hello.
I know this may be a convulted mess of code but I have spent all day googling, experimenting, and reading tutorials, but to no avail. Can anyone assist?
I want to store sessions in a MySql database to avoid security issues on a shared host. I cannot get this to write my sessions anywhere. Here is the code with questions to follow...
My table - php_session
Fields
session_id
last_updated
session_data
function _open()
{
$server = "localhost";
$username = "user";
$password = "password";
$database = "mydb";
mysql_connect($server, $username, $password) or die(mysql_error());
mysql_select_db($database) or die("No database selected!!");
return true;
}
function _close()
{
mysql_close();
return true;
}
function _read($id)
{
$id = mysql_real_escape_string($id);
$sql = "SELECT session_data FROM php_session WHERE session_id = '$id'";
if ($result = mysql_query($sql)) {
if (mysql_num_rows($result)) {
$record = mysql_fetch_assoc($result);
return $record['session_data'];
}
}
return '';
}
function _write($id, $data)
{
$access = time();
$id = mysql_real_escape_string($id);
$access = mysql_real_escape_string($access);
$data = mysql_real_escape_string($data);
$sql = "REPLACE INTO php_session(session_id, last_updated, session_data) VALUES ('$id', '$access', '$data')";
return mysql_query($sql);
}
function _destroy($id)
{
$id = mysql_real_escape_string($id);
$sql = "DELETE FROM php_session WHERE session_id = '$id'";
return mysql_query($sql);
}
function _clean($max)
{
$old = time() - $max;
$old = mysql_real_escape_string($old);
$sql = "DELETE FROM php_session WHERE last_updated < '$old'";
return mysql_query($sql);
}
session_set_save_handler('_open','_close','_read','_write','_destroy','_clean');
session_start();
Honestly, this code is not mine but an amalgamation of a few tutorials I have found. It is quite possible it is incorrect, but from I believe, I think it is ok. Still, I can't get it to do what I want.
Questions:
1) Do I need to make any function calls in order to have the session id written to the database? If so, how?
2) Do I need to adjust anything in the php.ini file?
3) Any other advice on how to make this relevant?
Thanks for any help. I can make all of this work when just using sessions in the default environment. Have been warned that is not safe and dbs are the way to go.