Local image cache for external images
When I want to cache some file, I'm typically doing it similar to your solution.

However, you're able to do most of this with built-in functionality, making the code a lot shorter:

&lt;?php
// Some URL for testing
$url = 'https://www.google.de/favicon.ico';

// Time to cache the files (here: 10 minutes)
define('time_to_cache', 600);

// Create a local file representation
$local = './cache/' . urlencode($url);

// Determine whether the local file is too old
if (@filemtime($local) + time_to_cache &lt; time()) {
    // Download a fresh copy
    copy ($url, $local);

    // Store headers in case we need them (see alternative below)
    file_put_contents($local . '.hdr', join($http_response_header, "\n"));
}

// Solution 1: Redirect to the local cache file
header('Location: ' . urlencode($local));
exit();

// Alternative: Send headers and the actual file
// Note that this might cause problems, e.g. due
// to cache fields and the like.

// Read and send headers
foreach(file($local . '.hdr') as $line)
    header($line);

// Read and send the actual file
readfile($local);


This doesn't include any error handling though.

For error handling, you might just want to check the results of the copy() operation. There's no need to request headers in advance or doing anything like that, since that will essentially delay you twice.

Regarding your implementation above:


Don't check the headers first. Just try downloading the file. This will take the same time. If you request headers first, you'll do two request, each of which might delay you by the mentioned 200-300 ms.
I've used urlencode() to create a working local filename. This might not be perfect depending on your actual file system though.
Don't check whether your local file exists first; you don't have to. You can just prepend filemtime() by an @, which will keep it from outputting any error messages and still return 0 in case the file doesn't exist (which will simply be interpretes as the file being ancient).
Why do you read the JPEG from your local disk and then reencoding it as a new image to be sent to the browser? Just send the actual file contents (or redirect the browser). The following will do the same without reencoding the image:

header('Content-type: image/jpeg');
readfile($local);