Cross‑Platform PHP Caching: File and Redis Strategies with Code Samples
This article explains how to implement cross‑platform caching in PHP using both file‑based storage and Redis, providing complete code examples, describing key functions for checking, reading, writing, and expiring cache entries, and highlighting compatibility considerations for different environments.
In PHP development, caching is essential for improving performance and response speed, and ensuring compatibility across different platforms is a key concern. The article presents two common caching approaches—file caching and Redis caching—along with complete code examples for each.
File Cache
File caching works on any platform. The following code demonstrates how to store and retrieve cached data using the filesystem, checking for existence and expiration (1 hour) before falling back to a data source.
<?php
function getCache($key) {
$cacheDir = '/tmp/cache/'; // cache directory
$filename = $cacheDir . md5($key) . '.txt'; // generate cache filename
if (file_exists($filename) && (time() - filemtime($filename) < 3600)) {
// Return cached data if file exists and is not expired
return file_get_contents($filename);
} else {
// Retrieve data from database or other source
$data = fetchDataFromDatabase($key);
// Store data in cache file
file_put_contents($filename, $data);
return $data;
}
}
function fetchDataFromDatabase($key) {
// Logic to query database or other data source
// ...
}
?>The code uses file_exists() to verify the cache file, filemtime() to check its age, file_get_contents() to read cached data, and file_put_contents() to write new data.
Redis Cache
Redis provides a fast, efficient caching solution. The example below shows how to connect to a Redis server, check for an existing, unexpired key, retrieve cached data, or fall back to a data source and store the result in Redis with an expiration time.
<?php
function getCache($key) {
$redis = new Redis();
if ($redis->connect('127.0.0.1', 6379)) {
// Connection successful
if ($redis->exists($key) && $redis->ttl($key) > 0) {
// Return cached data if it exists and is not expired
return $redis->get($key);
} else {
// Retrieve data from database or other source
$data = fetchDataFromDatabase($key);
// Store data in Redis cache
$redis->set($key, $data);
$redis->expire($key, 3600);
return $data;
}
} else {
// Fallback to file cache if Redis connection fails
return getCacheFromFile($key);
}
}
function fetchDataFromDatabase($key) {
// Logic to query database or other data source
// ...
}
function getCacheFromFile($key) {
// Use file cache as a backup strategy
// ...
}
?>This snippet uses the Redis extension to create a Redis instance, connect() to the server, exists() and ttl() to verify cache validity, get() to read cached data, set() to store data, and expire() to set the expiration time.
Overall, when using caching in PHP, developers should consider platform compatibility and choose the appropriate strategy—file or Redis—based on the deployment environment to achieve efficient caching, improved system performance, and better user experience.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
