Fixes ugly hack and unlikely but possible sql injection

This commit is contained in:
2026-04-01 22:51:38 +02:00
parent 668aabf4b8
commit b72ca8dbd2
3 changed files with 24 additions and 36 deletions
+3 -1
View File
@@ -17,6 +17,8 @@
]
},
"require": {
"php": ">=8.2"
"php": ">=8.2",
"ext-yaml": "*",
"ext-pdo": "*"
}
}
+8 -8
View File
@@ -3,14 +3,14 @@
namespace Kavalanche\SqlSessionHandler;
function config(string $key) {
$config = yaml_parse_file(__DIR__ . '/parameters.yaml');
$userConfigPath = __DIR__ . '/../../../../config/sql-session-handler.yaml';
if (file_exists($userConfigPath)) {
$userConfig = yaml_parse_file($userConfigPath);
$config = array_merge($config, $userConfig);
static $config = null;
if ($config === null) {
$config = yaml_parse_file(__DIR__ . '/parameters.yaml');
$userConfigPath = __DIR__ . '/../../../../config/sql-session-handler.yaml';
if (file_exists($userConfigPath)) {
$config = array_merge($config, yaml_parse_file($userConfigPath));
}
}
if (!empty($config[$key])) {
return $config[$key];
}
return $config[$key] ?? null;
}
+13 -27
View File
@@ -13,7 +13,13 @@ class SqlSessionHandler implements SessionHandlerInterface {
public function __construct(PDO $db) {
$this->db = $db;
$this->tableName = config('session-table-name');
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$tableName = config('session-table-name');
if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $tableName)) {
throw new \InvalidArgumentException("Invalid session table name: $tableName");
}
$this->tableName = $tableName;
}
public function close(): bool {
@@ -24,7 +30,7 @@ class SqlSessionHandler implements SessionHandlerInterface {
$sql = "DELETE FROM " . $this->tableName . " WHERE id = :id";
$stmt = $this->db->prepare($sql);
return $stmt->execute([
'id' => $id
'id' => $id
]);
}
@@ -54,31 +60,11 @@ class SqlSessionHandler implements SessionHandlerInterface {
}
public function write(string $id, string $data): bool {
/**
* Cannot use $this->read($id) because of php internal problem when open returns false
* Hence the ugly hack
*/
$sql = "SELECT data FROM " . $this->tableName . " WHERE id = :id";
$now = time();
$sql = "INSERT INTO " . $this->tableName . " (id, data, timestamp)
VALUES (?, ?, ?)
ON DUPLICATE KEY UPDATE data = ?, timestamp = ?";
$stmt = $this->db->prepare($sql);
$stmt->execute([
'id' => $id
]);
if ($stmt->fetch() === false) {
$sql = "INSERT INTO " . $this->tableName . " (id, data, timestamp) VALUES (:id, :data, :timestamp)";
$stmt = $this->db->prepare($sql);
return $stmt->execute([
'id' => $id,
'data' => $data,
'timestamp' => time()
]);
}
$sql = "UPDATE " . $this->tableName . " SET data = :data, timestamp = :timestamp WHERE id = :id";
$stmt = $this->db->prepare($sql);
return $stmt->execute([
'id' => $id,
'data' => $data,
'timestamp' => time()
]);
return $stmt->execute([$id, $data, $now, $data, $now]);
}
}