Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dazecoop/c161421023c5c05c09344aee9b55ee53 to your computer and use it in GitHub Desktop.
Save dazecoop/c161421023c5c05c09344aee9b55ee53 to your computer and use it in GitHub Desktop.
Clear image cache for Github markdown images with PHP cron script

Clear image cache for Github markdown images with PHP cron script

🤔 What?

As per this post dated back from 2015, there is an issue with Github caching images you've embedded in markdown, eg README.md files.

This script is a PHP cron that accepts an array of images & clears their cache.

It should be run at a fairly sensible interval that clears the cache of the image(s) you've specified.

🔥 How to run

Upload this to a PHP server, then just hit the URL of the file you've created.

To automate this, most hosting providers offer a cron solution. Simply curl to this file on your server, eg curl "https://YOUR_SERVER.com/PATH/TO/THIS_FILE.php". Example cron interval 0 4 * * * (04:00 every day).

🤓 The PHP cron script

// Show all PHP errors.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Array of images.
$images = [
  'https://camo.githubusercontent.com/...', // Update this to your image(s).
];

// Loop over each image.
foreach ($images as $image) {
  echo clearCache($image);
  echo "\n\n";
}

// Output done.
echo "\n\n== All done ==";

/**
 * Function to clear the cache for a given image URL.
 * @param $image
 * @return response from curl request
 */
function clearCache($image) {
  $curl = curl_init();

  curl_setopt_array($curl, [
    CURLOPT_URL => $image,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'PURGE',
  ]);

  $response = curl_exec($curl);
  curl_close($curl);

  return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment