Count and limit the number of files uploaded (HTML file input)

I have that basic, well known multiple file upload form. Something like that...

<input type="file" multiple="multiple" name="something[]" />

Is there a way (preferable a hard coded option) to limit the number of files that user can select? By limit i mean strictly blocked, not just a warning if number is exceeded.

Thanks in advance. :)


Solution 1:

You can implement a javascript solution to check the number of files that have been selected, which you can then use to forbid uploading to the server. There are really only going to be client-side solutions to this problem though, as there is really nothing stopping a user from posting these files to your php script anyway. You can specify a maximum upload size limit, but it isn't specific to the number of files that are being uploaded.

Your best bet is to implement some javascript checking, specifying a reasonable maximum upload size for your http server (or in PHP), and then ignoring any file uploaded if it exceeds your maximum count.

Read about the HTML5 File API here to restrict the count of selected files: http://dev.w3.org/2006/webapi/FileAPI/

Here is the php.ini docs which explain how to make a size limitation on uploads: http://php.net/manual/en/ini.core.php

As was suggested in the comments, check out: http://php.net/manual/en/ini.core.php#ini.max-file-uploads

Solution 2:

we all know that in an array first element is stored in 0 th index, 2nd in 1st index......nth in (n-1)th index

now you cant take count($_FILES['something']) which will always return 5 since there are 5 keys in the array

now the question is what does $_FILES['something']['name'][0] contains? => name of first file uploaded

so check like

if(empty($_FILES['something']['name'][0]))
{
     //checking whether a single file uploaded or not
     //if enters here means no file uploaded
     //so if you want you may put a check/validation here to make file
     //upload a must in your website
}
if(isset($_FILES['something']['name'][5]))
{
     //checking whether 6 files uploaded or not
     //so here you can put a check/validation to restrict user from
     //uploading more than 5 files
}

Solution 3:

Pure Js alternatives that do that and much more:

  • FineUploader. Demo

  • bluimp's jQuery File Upload Plugin. Usage: jquery file upload restricting number of files

They are also available at https://cdnjs.com/