1
0
mirror of https://github.com/vrana/adminer.git synced 2025-08-30 01:30:12 +02:00

Refactor working with a locked file

This commit is contained in:
Peter Knut
2024-10-07 22:20:32 +02:00
parent a494827dc5
commit a63fadd503
3 changed files with 40 additions and 31 deletions

View File

@@ -82,11 +82,11 @@ function build_http_url($server, $username, $password, $defaultServer, $defaultP
function add_invalid_login() {
global $adminer;
$fp = file_open_lock(get_temp_dir() . "/adminer.invalid");
if (!$fp) {
$file = open_file_with_lock(get_temp_dir() . "/adminer.invalid");
if (!$file) {
return;
}
$invalids = unserialize(stream_get_contents($fp));
$invalids = unserialize(stream_get_contents($file));
$time = time();
if ($invalids) {
foreach ($invalids as $ip => $val) {
@@ -100,7 +100,7 @@ function add_invalid_login() {
$invalid = array($time + 30*60, 0); // active for 30 minutes
}
$invalid[1]++;
file_write_unlock($fp, serialize($invalids));
write_and_unlock_file($file, serialize($invalids));
}
function check_invalid_login() {

View File

@@ -32,9 +32,9 @@ if (isset($_GET["file"])) {
}
if ($_GET["script"] == "version") {
$fp = file_open_lock(get_temp_dir() . "/adminer.version");
if ($fp) {
file_write_unlock($fp, serialize(array("signature" => $_POST["signature"], "version" => $_POST["version"])));
$file = open_file_with_lock(get_temp_dir() . "/adminer.version");
if ($file) {
write_and_unlock_file($file, serialize(["signature" => $_POST["signature"], "version" => $_POST["version"]]));
}
exit;
}

View File

@@ -1215,33 +1215,42 @@ function get_temp_dir() {
return $return;
}
/** Open and exclusively lock a file
* @param string
* @return resource or null for error
/**
* Opens and exclusively lock a file.
*
* @param string $filename
* @return resource|null
*/
function file_open_lock($filename) {
$fp = @fopen($filename, "r+"); // @ - may not exist
if (!$fp) { // c+ is available since PHP 5.2.6
$fp = @fopen($filename, "w"); // @ - may not be writable
if (!$fp) {
return;
}
chmod($filename, 0660);
}
flock($fp, LOCK_EX);
return $fp;
function open_file_with_lock($filename)
{
$file = fopen($filename, "c+");
if (!$file) {
return null;
}
/** Write and unlock a file
* @param resource
* @param string
chmod($filename, 0660);
if (!flock($file, LOCK_EX)) {
fclose($file);
return null;
}
return $file;
}
/**
* Writes and unlocks a file.
*
* @param resource $file
* @param string $data
*/
function file_write_unlock($fp, $data) {
rewind($fp);
fwrite($fp, $data);
ftruncate($fp, strlen($data));
flock($fp, LOCK_UN);
fclose($fp);
function write_and_unlock_file($file, $data)
{
rewind($file);
fwrite($file, $data);
ftruncate($file, strlen($data));
flock($file, LOCK_UN);
fclose($file);
}
/**