Ash
Ash

Reputation: 47

PHP Upload File Type, Size and Existence?

I am currently using this PHP code for upload function. I need to know how to add some file type validation for 1)extension, 2)file size limit and 3)to check that there is actually a file selected to upload.

Thanks for any help.

<?php
if(isset($_POST['submit'])){
    if(count($_FILES['upload']['name']) > 0){
        //Loop through each file
        for($i=0; $i<count($_FILES['upload']['name']); $i++) {
          //Get the temp file path
            $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

            //Make sure we have a filepath
            if($tmpFilePath != "tmp/"){

                //save the filename
                $shortname = $_FILES['upload']['name'][$i];

                //save the url and the file
                $filePath = "uploads/" . date('d-m-Y-H-i-s').'-'.$_FILES['upload']['name'][$i];

                //Upload the file into the temp dir
                if(move_uploaded_file($tmpFilePath, $filePath)) {

                    $files[] = $shortname;
                    //insert into db 
                    //use $shortname for the filename
                    //use $filePath for the relative url to the file

                }
              }
        }
    }

          header('Location: http://localhost/FloodMap/report.html');
          exit;
}
?>

Upvotes: 2

Views: 1829

Answers (2)

Sherif
Sherif

Reputation: 11943

  • Checking that a file was successfully uploaded

According to the manual PHP returns an error code in the $_FILES array. So for example...

if ($_FILES['upload']['error'] == UPLOAD_ERR_OK) {
    /* the file was uploaded successfully */
}
  • Checking the file extension

While the $_FILES array does provide an extension it is important to remember that this is client-supplied data and as such it cannot be trusted. In fact, the only thing in that array you can trust is the error and tmp_name, which PHP supplies. Everything else comes from the client.

So to verify that a file is somewhat what you expect, you would have to check the files magic MIME bytes against something like finfo_file

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $_FILES['upload']['tmp_name']);

$allowedMimes = ['image/jpg','image/gif','image/png'];

if (!in_array($mimeType, $allowedMimes, true)) {
    throw new FileException("File not allowed...");
}
  • Checking the file size

Again, as noted earlier, while the $_FILES array provides a size key to the upload, that is client-supplied data and should not be trusted. Instead just check with filesize($_FILES['upload']['tmp_name']) instead. That way you're checking the actual size of the file.


Bonus

FWIW, checking the file size at the server level (if the only intention is to tell the user this file is too big) makes for a rather horrible user experience. It's better to do that kind of thing at the client-level first so they know before they even bother uploading the file if it's too big.

In HTML5 we can do this with the File API. In your form just attach to some event listener like onchange or something and check the File.files[0].size to alert the user. You can do the same for the file type as well.

Of course, I'm not suggesting you don't check file size constraints on the server side if you need to for other purposes. Just saying, that on its own, if it's the only means of telling the user they uploaded a file that's too big, it cripples the user experience.

Upvotes: 1

Mani
Mani

Reputation: 2655

To Check file extension

$tmpFilePath = $_FILES['upload']['tmp_name'][$i];

    $imageFileType = pathinfo($tmpFilePath,PATHINFO_EXTENSION);

    if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
        echo "Only JPG, JPEG, PNG & GIF files are allowed.";
    }

To check file size

if ($_FILES["upload"]["size"][$i] > 500000) {
    echo "Sorry, your file is too large.";
}

To check is file received

if($_FILES['upload']['tmp_name'][$i]!=""){


}

Upvotes: 1

Related Questions