here i'm posting my PHP code for session using MySQL. please help me if there is any error or if it can be optimized or security can be enhanced !
Host:localhost, user:root, password "", database:pro
Table Structure
SessionID [pk] - Data - DateTouched
<?php
function open($sess_id, $sess_name) {
return true;
}
function close() {
return true;
}
function read($sess_id) {
$con = mysqli_connect("localhost", "root", "","pro");
$stmt = mysqli_prepare($con,"SELECT Data FROM sessions WHERE SessionID = ?");
mysqli_stmt_bind_param($stmt,"s",$sess_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$data);
mysqli_stmt_fetch($stmt);
mysqli_stmt_close($stmt);
$CurrentTime = date('Y-m-d H:i:s');
if (!isset($data))
{
$stmt = mysqli_prepare($con,"INSERT INTO sessions (SessionID, DateTouched) VALUES (?,?)");
mysqli_stmt_bind_param($stmt,"ss",$sess_id,$CurrentTime);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
return false;
}
else
{
$stmt = mysqli_prepare($con,"UPDATE sessions SET DateTouched = ? WHERE SessionID = ?");
mysqli_stmt_bind_param($stmt,"ss",$CurrentTime,$sess_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
return $data;
}
}
function write($sess_id, $data) {
$con = mysqli_connect("localhost", "root", "","pro");
$CurrentTime = date('Y-m-d H:i:s');
$stmt = mysqli_prepare($con,"UPDATE sessions SET Data= ?,DateTouched=? WHERE SessionID=?");
mysqli_stmt_bind_param($stmt,"sss",$data,$CurrentTime,$sess_id);
mysqli_stmt_execute($stmt);
return true;
}
function destroy($sess_id) {
$con = mysqli_connect("localhost", "root", "","pro");
$stmt = mysqli_prepare($con,"DELETE FROM sessions WHERE SessionID = ?");
mysqli_stmt_bind_param($stmt,"s",$sess_id);
mysqli_stmt_execute($stmt);
return true;
}
function gc($sess_maxlifetime)
{
$con = mysqli_connect("localhost", "root", "","pro");
$stmt = mysqli_prepare($con,"Delete from sessions where TIMESTAMPDIFF (Second ,DateTouched,now())>=?");
mysqli_stmt_bind_param($stmt,"s",$sess_maxlifetime);
mysqli_stmt_execute($stmt);
return true;
}
session_set_save_handler("open", "close", "read", "write", "destroy", "gc");
session_name('Session');
session_start();
?>