Skip to content

Instantly share code, notes, and snippets.

@AnrDaemon
Last active June 24, 2017 21:58
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 AnrDaemon/be47219525732a07bc05764ca85b0730 to your computer and use it in GitHub Desktop.
Save AnrDaemon/be47219525732a07bc05764ca85b0730 to your computer and use it in GitHub Desktop.
<?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);
}
<?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