Skip to content

Instantly share code, notes, and snippets.

@fakerybakery
Last active October 13, 2023 16:05
Show Gist options
  • Save fakerybakery/df33cb8890da4ebf9e46f8a72e486f00 to your computer and use it in GitHub Desktop.
Save fakerybakery/df33cb8890da4ebf9e46f8a72e486f00 to your computer and use it in GitHub Desktop.
file_get_contents caching in PHP

file_get_contents caching in PHP

If you enjoy this tool, please star this Gist! Author: fakerybakery (mrfakename). URL: https://gist.github.com/fakerybakery/df33cb8890da4ebf9e46f8a72e486f00

Heavily modified from: https://stackoverflow.com/a/18097502

Code:

function fgc($url) {
    $cache_file = 'cache/' . md5($url);
    if(file_exists($cache_file)) {
        if(time() - filemtime($cache_file) > 3600) {
            $cache = file_get_contents($url);
            file_put_contents($cache_file, $cache);
        } else {
            $cache = file_get_contents($cache_file);
        }
    } else {
        $cache = file_get_contents($url);
        file_put_contents($cache_file, $cache);
    }
    return $cache;
}

Modifications licensed under AGPL-3.0

<?php
# Modifications licensed under AGPL-3.0
# Inspired by https://stackoverflow.com/a/18097502
function fgc($url) {
$cache_file = 'cache/' . md5($url);
if (file_exists($cache_file)) {
if(time() - filemtime($cache_file) > 3600) {
$cache = file_get_contents($url);
file_put_contents($cache_file, $cache);
} else {
$cache = file_get_contents($cache_file);
}
} else {
$cache = file_get_contents($url);
file_put_contents($cache_file, $cache);
}
return $cache;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment