title: PHP Validating the File Upload
body: <p>I'm a PHP beginner and currently learning the "Validating the File Upload" part.</p>
  
  <p>I made a test.php page containing following code: </p>
  
  <pre><code>var_dump(@$_FILES['file']['type']);
  </code></pre>
  
  <p>First, I uploaded an image "img.gif" and it returned:</p>
  
  <pre><code>string 'image/gif' (length=9)
  </code></pre>
  
  <p>Then, I changed the image's extension to ".jpg" and it returned:</p>
  
  <pre><code>string 'image/jpeg' (length=10)
  </code></pre>
  
  <p>So I realized $_FILES["file"]["type"] only return the uploaded file extension but didn't actually check what file is it. </p>
  
  <p>In this page, <a href="http://www.w3schools.com/php/php_file_upload.asp">http://www.w3schools.com/php/php_file_upload.asp</a>, there is a code:</p>
  
  <pre><code>$allowedExts = array("gif", "jpeg", "jpg", "png");
  $extension = end(explode(".", $_FILES["file"]["name"]));
  if ((($_FILES["file"]["type"] == "image/gif")
  || ($_FILES["file"]["type"] == "image/jpeg")
  || ($_FILES["file"]["type"] == "image/jpg")
  || ($_FILES["file"]["type"] == "image/png"))
  &amp;&amp; ($_FILES["file"]["size"] &lt; 20000)
  &amp;&amp; in_array($extension, $allowedExts))
  </code></pre>
  
  <p>I'm wondering why above codes check file extension twice? I deleted some from above codes and this is my new code:</p>
  
  <pre><code>$allowedExts = array("gif", "jpeg", "jpg", "png");
  $extension = end(explode(".", $_FILES["file"]["name"]));
  if (($_FILES["file"]["size"] &lt; 20000) &amp;&amp; in_array($extension, $allowedExts))
  </code></pre>
  
  <p>Is my code correct? Or do you have any better ways to validate the upload file is a image?</p>
  
  <p>Thanks!</p>