Sunday, January 02, 2011

Setting limitation on uploading file, PHP

You can always set limitations on the uploading process as it is a big security risk to let users upload whatever they like ...
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>

More detailed types of files : 
"application/pdf" - PDF Files
"application/msword" - MS Word Files
"application/powerpoint" - MS Powerpoint Files
"application/excel" - MS Excel Files
"text/plain" - Text Files


Source : W3Schools

No comments: