title: Saving remote image with php
body: <p>The following code retrieves an image and saves it to a local folder. A jpg file is indeed saved to local disk, with around 40KB filesize (seems correct). When I put the local path in an img tag, the file does not display. </p>
  
  <p>Firebug > Inspect Element shows a size of 0 X 0 and I'm unable to view the image when saved to my desktop.</p>
  
  <p>file_put_contents, file_get_contents and getimagesize don't return FAILs. $url IS a valid image. The problem is just saving it locally, the file seems to be corrupt - how come?</p>
  
  <pre><code>$url = $image-&gt;request_url; //the image generated on the remote server
      //print_r(getimagesize($url)); die;
      $img = 'thumbalizr/cache/screenshot_' . $row['id'] . '.jpg'; //path to our local cache folder + unique filename
      if( !$captured_file = file_get_contents($url) ) die('file could not be retrieved');
      elseif( !file_put_contents($img, $captured_file, FILE_APPEND) ) die('file could not be written to local disk'); //write the image to our local cache
  </code></pre>
  
  <p>"Are you sure the path is correct? Have you tried an absolute path?" YES</p>
  
  <p>"Have you checked that the image is downloaded correctly, perhaps with another utility (e.g. ftp, diff)?" I can download the img via ftp but it does not open on my local computer either.</p>
  
  <p>"What do you get if you call the URL directly in the browser?" FF just prints out the URL instead of showing the image</p>
  
  <p>"Why are you using FILE_APPEND? if the target already exists, this writes to the end, which will naturally give you a corrupt image" I removed FILE_APPEND, no difference</p>
  
  <p>"source and final extension are the same?" Yes I tried with jpg, jpeg and png - no difference</p>
  
  <p>"First of all, example code is wrong. Can't use $capture_file in file_put_content because that variable is not defied becouso of if else if block logic." - WRONG, that code does run!</p>
  
  <p>"Can you look into the image file" - no! Although the file has a realistic file size and I can download it, it's impossible to open it.</p>