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);
      fflush($fp);    // need to insert this line for proper output when tile is first requestet

to this cleaner version:

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

and then to the even shorter:

    $contents = file_get_contents($url);

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(
		'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);

(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.