Wednesday, January 12, 2011

Handling File Uploads with PHP

Lets have a look how to handle a file upload using PHP.
First we need to create a form to upload our file as below.
Allowing people to upload files to your web site is putting you in risk, unless you do not check what they are uploading. In this example we are checking the file size and the file type of the uploaded file. Below PHP is going to do the rest for you. The uploaded files are going to save in a folder "upload". Rename it with your folder name.

$imgName = $_FILES["file"]["name"];

if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < $_POST['MAX_IMG_SIZE']))  {
  if ($_FILES["file"]["error"] > 0)
    {
 echo "File upload Error.";
 echo "Return Code: " . $_FILES["file"]["error"];
    }
  else
    {
    if (file_exists("../upload/".$imgName))
      {
       echo imgName . " already exists. ";
      }
    else
      {
       move_uploaded_file($_FILES["file"]["tmp_name"],"../upload/" . $imgName);
       echo "File stored in: " . "upload/" . $_FILES["file"]["name"];
 
      }
    }
  }
else
  {
   echo "Invalid file type or file size too large";
  }

No comments:

Post a Comment