Skip to content

Instantly share code, notes, and snippets.

@fwarren
Created September 2, 2017 02:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwarren/caa80af5bccf246fa24cdc3650786fef to your computer and use it in GitHub Desktop.
Save fwarren/caa80af5bccf246fa24cdc3650786fef to your computer and use it in GitHub Desktop.
File Hash to multiple Subdirectoris
<?php
// https://stackoverflow.com/questions/23787785/how-to-use-hash-function-for-storing-4-million-images-in-file-system
// $id = A unique identifier (a filename)
// It could be useful to make this id the same for the original,
// as well as any thumbnails. Your image and variants will all
// then end up in the same directory.
// $levels_deep = The number of directories deep you want to go.
// Want more levels? Use a hashing method with a longer
// output, such as sha1 (40 characters).
function _getDir($id, $levels_deep = 32) {
$file_hash = md5($id);
$dirname = implode("/", str_split(
substr($file_hash, 0, $levels_deep)
));
return $dirname;
}
function _store($dirname, $filename) {
// The `true` flag here will have `mkdir` create directories recursively.
if(!file_exists($dirname) && !mkdir($dirname, 0777, true))
throw new Exception("Could not create directory " . $dirname);
return file_put_contents(
$dirname . "/" . $filename,
"Contents of example file.\n"
);
}
// Example
store(getDir("myfile.jpg", 4), "myfile.jpg");
@willbprog127
Copy link

This is fabulous! 🌮

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment