title: Secure User Image Upload Capabilities in PHP
body: <p>I'm implementing a user-based image uploading tool for my website.  The system should allow any users to upload JPEG and PNG files only.   I'm, of course, worried about security and so I'm wondering how the many smarter people than myself feel about the following checks for allowing uploads:</p>
  
  <p>1) First white list the allowable file extensions in PHP to allow only PNG, png, jpg, JPG and JPEG.  Retrieve the user's file's extension via a function such as:</p>
  
  <pre><code>return end(explode(".", $filename));
  </code></pre>
  
  <p>This should help disallow the user from uploading something malicious like .png.php.  If this passes, move to step 2.</p>
  
  <p>2) Run the php function getimageize() on the TMP file. Via something like:</p>
  
  <pre><code>getimagesize($_FILES['userfile']['tmp_name']);
  </code></pre>
  
  <p>If this does not return false, proceed.</p>
  
  <p>3) Ensure a .htaccess file is placed within the uploads directory so that any files within this directory cannot parse PHP files:</p>
  
  <pre><code>php_admin_value engine Off
  </code></pre>
  
  <p>4) Rename the user's file to something pre-determined. I.E.</p>
  
  <pre><code>$filename = 'some_pre_determined_unique_value' . $the_file_extension;
  </code></pre>
  
  <p>This will also help prevent SQL injection as the filename will be the only user-determined variable in any queries used.</p>
  
  <p>If I perform the above, how vulnerable for attack am I still?  Before accepting a file I should hopefully have 1) only allowed jpgs and pngs, 2) Verified that PHP says it's a valid image, 3) disabled the directory the images are in from executing .php files and 4) renamed the users file to something unique.</p>
  
  <p>Thanks,</p>