Created
October 29, 2020 13:08
-
-
Save epixian/afe77d384ef0faac84310d28f41a96da to your computer and use it in GitHub Desktop.
PHP tempdir helper function
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 | |
if (!function_exists('tempdir')) { | |
/** | |
* Create a unique temporary directory and return its path. | |
* | |
* Insipired by | |
* @link https://stackoverflow.com/questions/1707801/making-a-temporary-dir-for-unpacking-a-zipfile-into | |
* | |
* @param string $prefix | |
* @param integer $mode | |
* @param boolean $auto_delete | |
* @return string | |
*/ | |
function tempdir($prefix = 'tmp', $mode = 0700, $auto_delete = true) | |
{ | |
// abort if prefix contains unsafe characters | |
if (strpbrk($prefix, '\\/:*?"<>|') !== false) { | |
return false; | |
} | |
// create the directory | |
do { | |
$dirname = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $prefix . Str::random(8); | |
} while (!@mkdir($dirname, $mode)); | |
// clean up the filesystem when done | |
if ($auto_delete) { | |
// anonymous since we REALLY don't want to expose this functionality to general use | |
$destroy_dir_func = function ($dirname) use (&$destroy_dir_func) { | |
if (!is_dir($dirname)) { | |
return false; | |
} | |
$files = array_diff(scandir($dirname), ['.', '..']); | |
foreach ($files as $file) { | |
if (is_dir($dirname . DIRECTORY_SEPARATOR . $file)) { | |
$destroy_dir_func($dirname . DIRECTORY_SEPARATOR . $file); | |
} else { | |
unlink($dirname . DIRECTORY_SEPARATOR . $file); | |
} | |
} | |
return rmdir($dirname); | |
}; | |
register_shutdown_function($destroy_dir_func, $dirname); | |
} | |
return $dirname; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment