Created
June 22, 2011 23:14
-
-
Save GromNaN/1041522 to your computer and use it in GitHub Desktop.
Temporary directory deleted when PHP ends.
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 | |
/** | |
* Temporary directory deleted when PHP ends. | |
* | |
* @author Jérôme Tamarelle <jerome@tamarelle.net> | |
*/ | |
final class TempDir | |
{ | |
private static $instances = array(); | |
private $path; | |
/** | |
* Delete all created directories. | |
*/ | |
public static function purge() | |
{ | |
self::$instances = array(); | |
} | |
/** | |
* Create a directory with an unique name | |
* | |
* @param string $dir The directory where the temporary directory will be created. | |
* @param string $prefix The prefix of the generated temporary directory. | |
* | |
* @return string Path to the new temp directory | |
*/ | |
public static function create(string $dir = null, string $prefix = null) | |
{ | |
return strval(new self($dir, $prefix)); | |
} | |
/** | |
* Create a directory with an unique name | |
* | |
* @param string $dir The directory where the temporary directory will be created. | |
* @param string $prefix The prefix of the generated temporary directory. | |
*/ | |
private function __construct(string $dir = null, string $prefix = null) | |
{ | |
$this->path = tempnam($dir ?: sys_get_temp_dir(), $prefix ?: ''); | |
unlink($this->path); | |
mkdir($this->path); | |
self::$instances[] = $this; | |
} | |
/** | |
* Delete the directory when it's over. | |
*/ | |
private function __destruct() | |
{ | |
exec(sprintf('rm -rf "%s"', $this->path)); | |
} | |
private function __toString() | |
{ | |
return $this->path; | |
} | |
} |
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 | |
include 'TempDir.php'; | |
$dir = TempDir::create(); | |
var_dump(is_dir($dir)); // True | |
touch($dir.'/file1'); // OK | |
TempDir::purge(); | |
var_dump(is_dir($dir)); // False but PHP says True | |
touch($dir.'/file2'); // Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment