Click here to Skip to main content
15,902,939 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a web form in which users can upload one or more files. I've already handled the client-side and server-side code for uploading the files.

But in my case, all files are uploaded to a single directory. But I want to save uploaded files in multiple directories.
I've read somewhere it won't be so efficient to store all uploaded files in a single directory if number of files get too many.

Now, I want to check if the number of files in the last used(newest) directory exceeds "N",PHP creates a new directory and then save uploaded files to the new directory and this validation and directory creation repeats on each file upload...

I appreciate if you could provide me with a solution.

Besides,please notice a corner case, in which for example In my directory 'A',I have (N-1) files and in a single form submission,user uploads for example 3 files. How should I handle the file saving process in this case?

Thanks in advance.

1 solution


If you are using PHP5 then there is a function named scandir[^] This function can be used to first locate the newest folder in a path something like shown below.
$dirs = scandir('data', SCANDIR_SORT_DESCENDING);
$newest_dir = $dirs[0];

Once you locate the correct the folder then all you have to do is to count the number of files. WHich can be done using code similar to shown below

Now if the count returned by above code is less than equal to max_allowed then you can copy the files in that folder else create a new folder first and copy the files in that newly created filter.
As far as boundary condition is concerned, you can keep copying the files to the latest folder found using scandir in a loop, till the count is <= the threshold. Once count reaches the threshold create a new folder and start copying to it.

Share this answer
Member 11033015 26-Jan-15 14:13pm    
Thanks for your solution Prasad. I'll try it and modify my code according to your solution. One more question, could you please explain the "[!\.]*" part in glob function pattern parameter?
Prasad Khandekar 26-Jan-15 14:14pm    
That omits . & .. folders.
Member 11033015 26-Jan-15 14:22pm    
I'm sorry, I don't understand.omitting . & .. folders? You mean you want to omit folders in counting directory?Am I right?
Prasad Khandekar 26-Jan-15 14:31pm    
Basically it won't count . & .. folders. Thus will return you the exact file count.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900