title: PHP/ curl/file_get_contents. Security and file size and type verification when getting remote files
body: <p>I want to enable users to copy or download images from a remote url or upload files (that may include pdfs and txt files etc. ) from their computer.  To do this, I have experimented with file_get_contents and curl both of which my host supports.  For the local uploads, I am just using php.  They do the basic job of transferring the data.  However, I am trying to find the best way to validate the contents of the file to avoid propagation of malicious code or loading up my server with excessively large files.</p>
  
  <p>In many cases, the file will be dynamically generated and therefore not end in a known extension so checking file extensions is not an option, besides lacking security.</p>
  
  <p>Using the mime type from the headers is one option and I have code to do that.</p>
  
  <pre><code>$file_info = new finfo(FILEINFO_MIME);  // object oriented approach!
  $mime_type = $file_info-&gt;buffer(file_get_contents($file));  // e.g. gives "image/jpeg"
  
  switch($mime_type) {
      case "image/jpeg":
          // your actions go here...
  }
  </code></pre>
  
  <p>However, it is evidently not too hard to spoof mime type.</p>
  
  <p>A few posts suggest sniffing out the magic numbers at the beginning of files but these too can be spoofed.</p>
  
  <p>For the limited case of images, one can use </p>
  
  <pre><code>$imginfo_array = getimagesize($tempFile); 
  </code></pre>
  
  <p>As far as I know, this does not work for pdfs, docs etc.</p>
  
  <p>Even taken together these methods do not seem very robust.  Yet numerous sites routinely allow you to upload, pin or otherwise get remote files and have somehow managed security issues.</p>
  
  <p>Would appreciate suggestions on best security and verification practices-as in curl vs. file_get_contents vs. wd--as well as other libraries or other techniques for obtaining file size and file type before transferring to my server.</p>
  
  <p>Note: I want to allow transfers of mainstream image formats such as .jpg and .gif and uploads of pdf files, doc and docx files, xls files, and similar common formats.</p>
  
  <p>Thanks in advance for recommendations and advice.</p>