Skip to content

Instantly share code, notes, and snippets.

@GromNaN
Created June 22, 2011 23:14
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 GromNaN/1041522 to your computer and use it in GitHub Desktop.
Save GromNaN/1041522 to your computer and use it in GitHub Desktop.
Temporary directory deleted when PHP ends.
<?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;
}
}
<?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