What's the most efficient way to grab a list of new files after a given date in php, or perhaps using a system call?
I have full control over how the files are stored as I receive them, so I thought maybe storing them in a folder structure like year/month/day/filename would be best, then all I have to do is scan for the directories greater than or equal to the date I want to retrieve using scandir and casting the directory name to int values. But I am not sure if I'm missing something that would make this easier/faster. I'm interested in the most efficient way of doing this as there will be a lot of files building up over time and I don't want to have to rescan old directories. Basically the directory structure should lend itself well to efficient manual filtering but I wanted to check to see if I'm missing something.
Simple example usage:
'2012/12/1' contains files test1.txt, test2.txt
'2012/12/2' => test3.txt, test4.txt
'2011/11/1' => test5.txt
'2011/11/2' => test6.txt
If I search for files on or after 2011/11/2, then I want everything except test5.txt to be returned.
Thanks in advance for any insight!
edit: the storing and actual processing of files are two separate processes, so I can't just process them as they come in which would obviously be the best solution.
Generally speaking I create directories like YYYY/MM/DD to store my files, often with another level for different sources. Sometimes I'll use YYYY-MM/DD or something similar. Note that there are only 3652 days in a decade, so you could even have a single level like YYYY-MM-DD and not get directories that are so large that they're hard to work with. If you have a filesystem that indexes directories, you can easily have 10s of thousands of files in a directory, otherwise one thousand should probably be your upper limit.
To process the files, I don't bother doing any actual searching of directory names. Since I know what date I'm interested in, I can simply generate the paths and scan only the directories containing files in the proper date range.
For example, let's say I want to process all files for the past week:
for $date = today() - 7 to today():
$path = strftime("%Y/%m/%d", $date)
for $filename in getFiles($path):
processFile($path, $filename)
It looks like you are on either linux or mac based on how you wrote your path.
The find command can return a list of files modified (or accessed) within a certain date.
// find files that were modified less than 30m ago
$filelist = system("find /path/to/files -type f -mmin -30");
I think system calls should be used sparingly since they reduce portability.
Storing in directories as you mentioned makes sense as it will reduce the search space.
Related
I currently have this function:
function getUploadedImages() {
$dir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads';
$images = glob("$dir/*.{jpg,png,jpeg}", GLOB_BRACE);
usort($images, function($a,$b){
return filemtime($b) - filemtime($a);
});
return array_slice($images, 0, 10);
}
At the start of the function, the $images array will contain every single file in the uploads directory.
Is there a way to avoid this, so that glob() won't have to return 100.000 files or more as the uploads folder grows?
I only need the newest N files, so it seems unnecessary to get all the other files that I don't need
Unfortunately you cannot avoid retrieving all file names using e.g. glob, then filtering the list to find the most recent ones.
However, even if it were possible, the way you are storing the uploaded files may cause problems in the future. If you really expect files numbering in the hundreds of thousands, the glob will get slower as the file system has trouble churning through the many files in the same directory.
May I suggest that you put uploaded files in subdirectories according to year, month, and (if needed) day? You would have a structure like:
- 2019
- 12
- 18
- file1.jpg
- file2.jpg
- 19
- file3.jpg
- file4.jpg
In this case, finding the most recent files is a case of finding the most recent date, walking through the directory tree, and getting the filenames. If you need more files, pick the next earlier date and so on. If you're looking for the 10 most recent files or so, this process should be faster than globbing a very long list of files.
In addition, this approach does not require a database.
Is there a way to avoid this
No it is not. Underlying filesystem does not provide this type of information so whatever way you go you (even with ordinary ls) you will have to scan all the items in given directory. However, if these files are stored there by you, you can store this information i.e. in database or flat file and then, use that "index" file for your task instead of touching physical files.
I know how to use glob() to fetch all image files in a directory, but I want to save retrieval time and only fetch the ones I need in the first place.
I am building a car dealership website, and there is a directory where all the vehicle photos get stored. Photos that are associated with a vehicle for sale start with the letter "v" and then the database ID, and then a dot before the model of vehicle.
Here is a sample list of files in a directory:
v313.2014.toyota.camry.0.jpg
v313.2014.toyota.camry.1.jpg
fordfusion.jpg
fordfusion2.jpg
v87.2015.honda.civic.0.jpg
v87.2015.honda.civic.1.jpg
2014.ford.escape.0.jpg
2014.ford.escape.1.jpg
Out of those files, only fordfusion.jpg, fordfusion2.jpg, 2014.ford.escape.0.jpg, 2014.ford.escape.1.jpg should be returned by glob().
I hope this is possible without retrieving all the image files and then going through the array with a regex because 90% of the images being fetched wouldn't be necessary.
I hope this is possible without retrieving all the image files and then going through the array with a regex because 90% of the images being fetched wouldn't be necessary.
Unless there is an extremely large number of files in the directory, this isn't worth worrying about. glob() internally has to iterate through all files in the folder to check their names against the pattern anyway; doing it in PHP code with a regular expression will perform equally well.
If there really is a very large number of files in the directory… don't do that. Large directories perform very poorly in general, and many filesystems have limits on the number of files in a folder. (For instance, the ext3 file system, common on older Linux systems, has a limit of around 32,768 files in a single directory.) Split them up into multiple directories.
To answer the question directly, though, there is no way to do this with a glob() pattern. It's possible to match all the files that do have names starting that way, but there's no way to invert the match. (You could check for [^v]* and v[^0-9]* as two separate patterns, but there's no way to combine them into a single pattern.)
if you're confident that files you don't want to retrieve starts with the letter v or starts with v followed by any digit you can try use the following regex
^[^v]+$|^v[^\d].+
check the Demo
I have ~280,000 files that will need to be searched through, and the proper file returned and opened. The file names are exact matches of the expected search terms.
The search terms will be taken by an input box using PHP. What is the best way to accomplish this so that searches do not take a large amount of time?
Thanks!
I suspect the file system itself will struggle with 280,000 files in one directory.
An approach I've taken in the past is to put those files in subdirectories based upon the initial letters of the filename e.g.
1/100000.txt
1/100001.txt
...
9/900000.txt
etc. You can subdivide further using the second letter etc.
Its good you added mysql to your tags. Ideally i would have a CRON task that would index the directories into a mysql table and use that to do the actual search. Algebra is faster than File System iteration. You could run the task daily or hourly depending on how often your files change. Or use something like Guard to monitor the file system for changes and make appropriate updates.
See: https://github.com/guard/guard
I'm currently building an application that will generate a large number of images (a few tens of thousand of images, possibly more but not in the near future at least). And I want to be able to determine whether a file exists or not and also send it to clients over http (I'm using apache is my web server).
What is the best way to do this? I thought about splitting the images to a few folders and reduce the number of files in each directory. For example lets say that I decide that each file name will begin with a lower letter from the abc. Than I create 26 directories and when I want to look for a file I will add the name of the directory first. For example If I want a file called "funnyimage2.jpg" I will save it inside a directory called "f". I can add layers to that structure if that is required.
To be honest I'm not even sure if just saving all the files in one directory isn't just as good, so if you could add an explanation as to why your solution is better it would be very helpful.
p.s
My application is written in PHP and I intend to use file_exists to check if a file exists or not.
Do it with a hash, such as md5 or sha1 and then use 2 characters for each segment of the path. If you go 4 levels deep you'll always be good:
f4/a7/b4/66/funnyimage.jpg
Oh an the reason its slow to dump it all in 1 directory, is because most filesystems don't store filenames in a B-TREE or similar structure. It will have to scan the entire directory to find a file often times.
The reason a hash is great, is because it has really good distribution. 26 directories may not cut it, especially if lots of images have a filename like "image0001.jpg"
Since ext3 aims to be backwards compatible with the earlier ext2, many of the on-disk structures are similar to those of ext2. Consequently, ext3 lacks recent features, such as extents, dynamic allocation of inodes, and block suballocation.[15] A directory can have at most 31998 subdirectories, because an inode can have at most 32000 links.[16]
A directory on a unix file system is just a file that lists filenames and what inode contains the actual file data. As such, scanning a directory for a particular filename boils down to the equivalent operation of opening a text file and scanning for a line with a particular piece of text.
At some point, the overhead of opening that directory "file" and scanning for your filename will outweigh the overhead of using multiple sub-directories. Generally, this won't happen until there's many thousands of files. You should benchmark your system/server to find where the crossover point is.
After that, it's a simple matter of deciding how to split your filenames into subdirectories. If you're allowing only alpha-numeric characters, then maybe a split based on the first 2 characters (1,296 possible subdirs) might make more sense than a single dir with 10,000 files.
Of course, for every additional level of splitting you add, you're forcing the system to open yet another directory "file" and scan for your filename, so don't go too deep on the splits.
your setup is okay. Keep going this way
It seems that you are on the right path. Another post at ServerFault seems to confirm that you are doing the right thing.
I think linux has a limit to the amount of files a directory can contain; it might be best to split them up.
With your method, you can have the same exact image with many different file names. Also, you'll have more images that start with "t" than you would "q" so the directory would still get large. You might want to store them as MD5-HASH.jpg instead. This will eliminate duplicates and have a more even distribution over 36 directories.
Edit: Like Evert mentions, you can do a multi-level directory structure to keep the directory size even smaller.
its more to a architecture related question, sorry if i ask in the wrong stack.
do they put them in a large pile im a folder ?
like
$uid.$md5(random).$name save in one
folder
folder/5231.124wdadace123214.arandomname.jpg
folder/42.15125dawdaowdaw232.arandom2name.png
folder/etc
or
$uid/$md5(random).$name
5231(uid)/12421adwawda2321.arandomname.jpg
42/15125awdawdwadwa232.arandom2name.png
etc/2323awdwadwadaw.logo.png
what im thinking here is the second one is better?
because at windows i have a lot of pics in one folder
and yes it takes time to open it.
do you guys have any idea how they keep the files ?
I wrote a function for my sites that converts user ids into a two level subdirectory hierarchy that limits subdirectories to 1000 at each level.
function get_image_dir($gid) {
$d = str_split(str_pad($gid, 6, "0", STR_PAD_LEFT), 3);
$wdir = "/images/members/" . $d[0] . "/" . $d[1] . "/" . $gid;
return $wdir;
}
(I actually add a third level with the raw user id to handle the rollover at 1,000,000.
/images/members/000/001/1
/images/members/000/002/2
...
/images/members/999/999/999999
/images/members/000/000/1000000
/images/members/000/001/1000001
Within those subdirectories, I further segregate based on
albums (organized by members)
various resizings (for different
places on the site
Final structure looks something like
/images/members/000/001/1/album1/original
/images/members/000/001/1/album1/50x50
/images/members/000/001/1/album1/75x75
/images/members/000/001/1/album1/400x300
The str_split(str_pad()) in the function probably isn't optimal, but for now it works.
This depends mainly on the filesystem. For a modern filesystem like NTFS or ext3, keeping huge numbers of files in the same directory is not a problem, but some older filesystems could not handle it.
However, it may still be a good idea to partition the files into subdirectories according to some scheme, just to keep them manageable with various tools (which may have their own issues with humongous directories) such as backup. BTW, opening a directory in Windows explorer counts as such a case.
it depends how many images you're expecting to have if we're talking about thousand keeping the pictures in diffrent folders make's it easier for the computer to scan the directory for the file
The way i do it is using folder which contain id numbers,
/img/0-100/1
/img/101-200/102
This will give you an easy way of looking up your images and the folder will stay quite small.
And there's no extension because i save this in the database.
Yes, lots of files in one folder can slow down seeks for files in that folder. At least in the major OSs. In theory it doesn't have to be that way.
Other sites use the date too. Not just user ids or image ids. Just another way to do the same thing.