How can PHP be used to efficiently cache files on the server while simultaneously allowing the client to download them?

To efficiently cache files on the server while allowing the client to download them, you can use PHP to check if the file exists in the cache directory before serving it. If the file exists, you can send it to the client with appropriate headers to indicate caching. If the file does not exist in the cache, you can fetch it from the original source, save it to the cache directory, and then serve it to the client.

$cacheDir = 'cache/';
$originalFile = 'path/to/original/file.txt';
$cacheFile = $cacheDir . basename($originalFile);

if (file_exists($cacheFile)) {
    // Send cached file to client
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($cacheFile) . '"');
    readfile($cacheFile);
} else {
    // Fetch file from original source
    copy($originalFile, $cacheFile);
    
    // Send file to client
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($cacheFile) . '"');
    readfile($cacheFile);
}