Caching is a technique used to store a copy of a given resource and serve it to reduce the time taken to retrieve the resource from the source. Implementing caching in PHP can greatly enhance the performance of web applications.
<?php
// Start the session
session_start();
// Simple file caching example
function getCachedData($filename, $cacheTime = 3600) {
// Check if cache file exists and is still valid
if (file_exists($filename) && (time() - filemtime($filename) < $cacheTime)) {
// Read from cache
return file_get_contents($filename);
} else {
// Fetch fresh data (could be a database query or API call)
$data = "This is fresh data. Current time: " . date('Y-m-d H:i:s');
// Save fresh data to cache
file_put_contents($filename, $data);
return $data;
}
}
// Filename for caching
$cacheFile = 'cache/data_cache.txt';
// Get data from cache or generate new data
$output = getCachedData($cacheFile);
// Output the data
echo $output;
?>
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?