PHP: Detecting fopen() failures when downloading images-Collection of common programming errors

I have a card game (screenshot below) in which I display player avatars.

For the avatars I’ve written a short proxy.php script, which would take an image URL passed to it as ?img= parameter, download it and save under /var/www/cached_avatars/md5_of_that_url at my CentOS 5 machine. Next time the script is called with the same URL, it will find that image in the dir and serve it directly to STDOUT.

This works mostly well, but for some avatars the initial download fails (I suppose it times out) and you don’t see the lower part of the player picture:

I’d like to detect this image download failure and delete the cached partial file, so that it is re-downloaded on the next proxy.php call.

I’ve tried detecting STREAM_NOTIFY_FAILURE or STREAM_NOTIFY_COMPLETED events in my callback, but they are not fired. The only events I see are: STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_MIME_TYPE_IS, STREAM_NOTIFY_FILE_SIZE_IS, STREAM_NOTIFY_REDIRECTED, STREAM_NOTIFY_PROGRESS:

Nov  3 18:48:27 httpd: 2  0
Nov  3 18:48:27 httpd: 4 image/jpeg 0
Nov  3 18:48:27 httpd: 5 Content-Length: 45842 0
Nov  3 18:48:27 httpd: 7  0
Nov  3 18:48:27 last message repeated 16 times
Nov  3 18:48:39 httpd: 2  0
Nov  3 18:48:40 httpd: 4 image/jpeg 0
Nov  3 18:48:40 httpd: 5 Content-Length: 124537 0
Nov  3 18:48:40 httpd: 7  0

And my even bigger problem is, that I can’t pass variables like $img or $cached into the callback or I can’t set a $length variable in the callback on a STREAM_NOTIFY_FILE_SIZE_IS event and then compare it with filesize($cached) in the main script (I could detect the mismatch and delete the file):

Nov  3 18:50:17 httpd: PHP Notice:  Undefined variable: length in /var/www/html/proxy.php on line 58
Nov  3 18:50:17 httpd: length=

Does anybody have a solution for my problem?

I’ve looked at the PHP curl library, but don’t see how could it help me here.

Below is my script, I’ve omitted the URL sanity checks for brevity:

Originally posted 2013-11-19 13:16:45.