Link to home
Start Free TrialLog in
Avatar of PeterErhard
PeterErhard

asked on

Validate Upload Script

I'll be allowing users to upload certain files on my website and have put together the below script.

Can anyone see any problems with it? Any suggested improvements?

<?php

      $FileUploadSuccess = 0;

      $uploaddir = 'files/';
      $uploadfile = $uploaddir . $_FILES['img1']['name'];

      $filetypes = array("image/jpg","image/gif","image/jpeg","image/pjpeg");
      $imageinfo = getimagesize($_FILES['img1']['tmp_name']);

      //check file size is less than 2MB (below is bytes)
      if ($_FILES['img1']['size'] <=  2097152)
      {
            // upload the file only if the file type is of one listed above.
            if(in_array(strtolower($_FILES['img1']['type']),$filetypes))
            {
                  // rename the file.
                  $path_parts = pathinfo($uploadfile);
                  $uploadfile = $uploaddir.(substr($_FILES['img1']['name'],0,(strlen($_FILES['img1']['name'])-(strlen($path_parts['extension'])+1))).date("YmdHis").".".$path_parts['extension']);

                  if (move_uploaded_file($_FILES['img1']['tmp_name'], $uploadfile))
                  {
                        $FileUploadSuccess = 1;
                  }
            }
      }

      if ($FileUploadSuccess == 0)
      {
            echo "File Upload Failed for some reason - display error message with likely reasons";
      }
      else
      {
            echo "File Upload Successful - display happy message";
      }

?>
Avatar of babuno5
babuno5
Flag of India image

code looks fine
ASKER CERTIFIED SOLUTION
Avatar of as2003
as2003

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of PeterErhard
PeterErhard

ASKER

Thanks guys.

A question regarding $filetypes = array('image/jpg','image/gif','image/jpeg','image/pjpeg');

If I wanted to allow doc, pdf as well how would it look within the array there?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
oh, and ms word docs are 'application/msword'
Thanks :)