I am creating files and setting it’s names to be hashed representation of time()
using md5
function:
$encoded_data = ['some_data']; $file_name = md5(time()).'.json'; $path = base_path("../some_folder/"); file_put_contents($path.$file_name, $encoded_data);
What I do not understand is if I use scandir
with sorting order parameter to get those files:
foreach(array_diff(scandir($path, 1), ['.', '..']) as $file_name) { $files[] = base_path('../some_folder/').$file_name; }
will $files
array be really be sorted by date and time which is used as a file name?
Advertisement
Answer
Since hashing function like md5 are one-way only, the filename is useless as a sorting criteria. If you want to keep track of the very same timestamp you used for generating the md5 value, you’d have to keep a hash:timestamp table on record. If you did that, you wouldn’t need to run scandir
to begin with — you could simply read the file list from the reference table you’ve saved. (Assuming you keep it up to date with deleted files. Otherwise, it would show obsolete files.)
Is there a particular reason you need to use a md5-hash of the timestamp? Why not simply use the timestamp (with a prefix or otherwise) as the filename? Then you could simply sort alphabetically, ascending or descending, and have the files automatically in timewise order. This would be by far the simplest and most light-weight option.
If md5-hashes as file names is a must, and writing a reference table is not what you prefer, then you will have to loop through the files, or use usort
, and check the date of the file’s creation/modification (filemtime
). You can find solutions in the answers to sort files by date in PHP. Be aware that this will lead to plenty more disk activity (even if the results are cached).