Skip to content
This repository has been archived by the owner on Dec 30, 2024. It is now read-only.

Commit

Permalink
Concurrency handling
Browse files Browse the repository at this point in the history
  • Loading branch information
007hacky007 committed Oct 8, 2022
1 parent 83b0da1 commit 088f9ea
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Light, simple and standalone PHP in-file caching class
- All code in one file - no pointless drivers.
- Secure - every generated cache file have a php header with `die`, making direct access impossible even if someone knows the path and your server is not configured properly
- Well documented and tested
- Handles concurrency correctly via flock
- Supports PHP 5.4.0 - 7.1+
- Free under a MIT license

Expand Down
19 changes: 14 additions & 5 deletions src/PhpFileCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,22 @@ public function __construct($cacheDirPath = "cache/", $cacheFileName = "defaultc
*/
private function loadCacheFile() {
$filepath = $this->getCacheFilePath();
$file = @file_get_contents($filepath);

if(($fp = fopen($filepath, "r+")) === false)
throw new \Exception("Could not fopen $filepath");

if (flock($fp, LOCK_SH)) {
$file = fread($fp, filesize($filepath));
flock($fp, LOCK_UN);
} else {
throw new \Exception("Could not get the lock for $filepath");
}
fclose($fp);


if (!$file) {
unlink($filepath);
throw new \Exception("Cannot load cache file! ({$this->getCacheFilename()})");
throw new \Exception("Cannot read cache file! ({$this->getCacheFilename()})");
}

// Remove the first line which prevents direct access to the file
Expand Down Expand Up @@ -114,9 +125,7 @@ private function saveCacheFile() {
$cache["hash-sum"] = $this->getStringHash(serialize($cache));
$data = serialize($cache);
$firstLine = '<?php die("Access denied") ?>' . PHP_EOL;
$success = file_put_contents($this->getCacheFilePath(), $firstLine . $data) !== false;

if (!$success)
if(file_put_contents($this->getCacheFilePath(), $firstLine . $data, LOCK_EX) === false)
throw new \Exception("Cannot save cache");

return $this;
Expand Down

0 comments on commit 088f9ea

Please sign in to comment.