1
0
Fork 0
php-coding/11.test4.php

97 lines
2.8 KiB
PHP

<?php
class MySessionHandler implements SessionHandlerInterface
{
public function close(): bool
{
global $handle;
mysqli_close($handle);
return true;
}
public function destroy(string $id): bool
{
global $handle;
$stmt = $handle->prepare("delete from tb_session where session_key = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$result = $stmt->affected_rows;
$stmt->close();
return $result;
}
public function gc(int $max_lifetime): int|false
{
global $handle;
$lapse_time = time();
return $handle->query("delete from tb_session where session_time < ($lapse_time-$max_lifetime)");
}
public function open(string $path, string $name): bool
{
global $handle;
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$handle = new mysqli('localhost:3306', 'root', 'chenx221', 'db_database11');
$handle->set_charset('utf8mb4');
return true;
} catch (Exception $e) {
error_log("Failed to connect to database: " . $e->getMessage());
return false;
}
}
public function read(string $id): string|false
{
global $handle;
$stmt = $handle->prepare("select session_data from tb_session where session_key = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$session_data = null;
$stmt->bind_result($session_data);
$stmt->fetch();
$stmt->close();
if ($session_data != null) {
return $session_data;
} else {
return '';
}
}
public function write(string $id, string $data): bool
{
$id='pvqdqck4rurolsi7qaha4n4ul1';
global $handle;
$lapse_time = time();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$handle = new mysqli('localhost', 'root', 'chenx221', 'db_database11');
$handle->set_charset('utf8mb4');
$stmt = $handle->prepare("select session_data from tb_session where session_key = ?");
$stmt->bind_param("s", $id, );
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows() == 0) {
$stmt2 = $handle->prepare("insert into tb_session values(?,?,?)");
$stmt2->bind_param("ssi", $id, $data, $lapse_time);
} else {
$stmt2 = $handle->prepare("update tb_session set session_data = ? , session_time = ? where session_key = ? ");
$stmt2->bind_param("sis", $data, $lapse_time, $id);
}
$stmt2->execute();
$result = $stmt2->affected_rows;
$stmt2->close();
$stmt->close();
return $result;
}
}
session_set_save_handler(new MySessionHandler());
session_start();
$_SESSION['user'] = 'mr';
$_SESSION['pwd'] = 'mrsoft';