Last active
June 24, 2017 21:58
-
-
Save AnrDaemon/be47219525732a07bc05764ca85b0730 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_new_image_name($dir, $id, $limit_num = PHP_INT_MAX) | |
{ | |
$cache = []; | |
foreach(glob($dir . sprintf('/%02u-*.*', $id), GLOB_MARK) as $name) | |
{ | |
if(is_dir($name)) | |
{ | |
continue; | |
} | |
if(preg_match('/^\d+\-(?P<counter>\d+)\_/', basename($name), $ta)) | |
{ | |
$cache[(int)$ta['counter']] = true; | |
} | |
} | |
if(count($cache) >= $limit_num) | |
throw new RuntimeException("Too many files already uploaded under this id.", 409); | |
$counter = 1; | |
while(isset($cache[$counter])) | |
{ | |
if($counter >= $limit_num) | |
throw new RuntimeException("Too many files already uploaded under this id.", 409); | |
$counter++; | |
} | |
// name = id-index_[sml|med|big].ext | |
return sprintf('%02u-%02u_', $id, $counter); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function get_new_image_name($dir, $id, $limit_num = null) | |
{ | |
$files = get_file_list($dir); // reads entire dir into an array | |
$counter = 0; | |
// name = id-index_[sml|med|big].ext | |
while(($name = sprintf('%02d', $id) . '-' . sprintf('%02d', ++$counter) . '_')) | |
{ | |
$notFound = true; | |
foreach ($files as $file) | |
{ | |
if ((strstr($file, $name) !== false)) | |
{ | |
$notFound = false; | |
break; | |
} | |
} | |
// Limit number of uploaded files | |
if ($notFound || ($limit_num !== null && $counter >= $limit_num)) | |
{ | |
return $name; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment