Skip to content

Instantly share code, notes, and snippets.

@filippotoso
Created January 22, 2018 17:58
Show Gist options
  • Save filippotoso/a0f375b873811f807fba141e84ec79d5 to your computer and use it in GitHub Desktop.
Save filippotoso/a0f375b873811f807fba141e84ec79d5 to your computer and use it in GitHub Desktop.
Get a temporary filename with a specific extension
/**
* Get a temporary filename with a specific extension
* @method temporary_filename
* @param string $dir The directory where it tries to create the temporary file
* @param string $extension The extension of the file (default: '')
* @param string $prefix The prefix of the file (default: '')
* @param integer $retry The number of times it tries to create a random filename (default: 100)
* @return string|FALSE
*/
function temporary_filename($dir, $extension = '', $prefix = '', $retry = 100) {
$extension = $extension == '' ? '' : '.' . $extension;
$dir = str_finish($dir, '/');
while ($retry > 0) {
$filename = $dir . $prefix . str_random(20) . $extension;
if (!file_exists($filename)) {
touch($filename);
return $filename;
}
$retry--;
}
return FALSE;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment