A lightweight proxy in PHP

I needed a quick lightweight proxy and was searching the web for some inspiration. This little 8-year-old snippet I found here is pretty neat.

<?php

function fetchURL() {

  if (isset($_POST["url"])) { // Check for the presence of our expected POST variable.

    $url = filter_var($_POST["url"], FILTER_SANITIZE_URL); // Be careful with posting variables.
    $cache_file = "cache/".hash('md5', $url).".html"; // Create a unique name for the cache file using a quick md5 hash.

    // If the file exists and was cached in the last 24 hours...
    if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) { // 86,400 seconds = 24 hours.

      $file = file_get_contents($cache_file); // Get the file from the cache.
      echo $file; // echo the file out to the browser.
    }

    else {

      $file = file_get_contents($url); // Fetch the file.
      file_put_contents($cache_file, $file, LOCK_EX); // Save it for the next requestor.
      echo $file; // echo the file out to the browser.
    }
  }

}

fetchURL(); // Execute the function

?>

Source: http://phillippuleo.com/articles/lightweight-caching-proxy-php

You can surly improve on sanitization and I wouldn’t use it like this for general caching but if you need to reduce the load on a free web service to stay in your quota or want to redirect some information you’re getting from a SaaS while keeping a local copy I think the approach is totally justifiable.