Skip to content


PHP image proxy not working? Check for leading junk…

I just wasted like half a day trying to figure out WTF was wrong with this PHP image-caching proxy. I was just not looking at the right place: I switched from this weird curl code:

      $ch = curl_init($url);
      $fp = fopen($file, "w");
      curl_setopt($ch, CURLOPT_FILE, $fp);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_exec($ch);
      curl_close($ch);
      fflush($fp);    // need to insert this line for proper output when tile is first requestet
      fclose($fp);

to this cleaner version:

    $handle = fopen($url, 'r');
    $contents = stream_get_contents($handle);
    fclose($handle);
    file_put_contents($cacheFile,$contents);

and then to the even shorter:

    $contents = file_get_contents($url);
    file_put_contents($cacheFile,$contents);

I even tried setting some custom request headers (yeah, my work computer is on a seriously locked network which makes me waste tons of time, turns out PHP just can’t fetch remote URLs from it), like:

	$opts = array(
	  'http'=>array(
		'method'=>"GET",
		'header'=>"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n".
			"Accept-Encoding: gzip, deflate\r\n".
			"Accept-language: en\r\n".
			"Cookie: foo=bar\r\n".
			"User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:16.0) Gecko/20100101 Firefox/16.0\r\n"
	  )
	);

	$context = stream_context_create($opts);
	
	//$contents = file_get_contents(urlencode($url),false,$context);
	$contents = file_get_contents($url,false,$context);
	file_put_contents($cacheFile,$contents);

(yes, it’s useless but I just don’t want to throw away those pieces of code)

Nothing help. In the end, I noticed that the output image of the PHP file was one byte larger than the actual cached image. So caching worked fine (well, actually it was network-blocked but I manually put a picture downloaded at home in the cache), but for some reason the script was adding something that messed up the picture. I bet you guessed already (or maybe not if you’re not used to PHP and header troubles?): there was just a leading space before the opening <?php tag……

Posted in web development.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Sorry about the CAPTCHA that requires JS. If you really don't want to enable JS and still want to comment, you can send me your comment via e-mail and I'll post it for you.

Please solve the CAPTCHA below in order to fight spamWordPress CAPTCHA