PHP, Programming

Creating a Directory, Adding Files and Deleting Everything

I was running a test and it came really handy to create a temporary directory, store some files in it, and later remove all the files and the directory itself.

$path = 'path/to/your/new/directory';

// Create directory if it doesn't already exist
if(!file_exists($path)) {
    mkdir($path, 0777, true);

// Add a text file
file_put_contents($path . 'text.txt', 'Hello World');

// Add a base64 image file
  'zQjO2xR9J+elr7PRPjpnpxAHBjch/1Kg3Yudv0GvQn7ZltKLmJKvp1cuc2eWUHnwGkPjt3' .
  '2zFBVCv2QG6BbocXtvcFAMfs3DbjApSaII6CAVQ1ZZBtkH1e3qZTz/jnL7Ds2ocswKplAF' .
  'DVNECegLiHU8PvmSqmgJWkDaIC5w54Zc9+HOCTiHSOZ6V+pSOzsg1xHXANdmw3i/jQ8CER' .
  'GHYC0o8i04FSH4kavLA2q3g4gA/zKgpeRHvGwPEaZBnKb9KgCLx/nEoppCMQj3CqeA98Z9' .
  'UfxwQDqF7sAtwF0MKTa2Z1+zzQIICRCdkFdPodoy2KUhBA3jD/A/xHYGEE6qVTAIezkxFk' .
  'AaVwyJRggk2boADxDGRhDkDwVPk7zqwH8k8bPsPfAhjleAtiLXwJOXoKj3h2xn/ehyXZuD' .
  'A1APzxG81O0vkU4DdUZ2lQNVMBebgUAKnFaZm8DAL/GxAJoAW62fWikjKAk5HxYgGM3/G5' .
  'RUm9pLgAUA9ibw5AeVjSR41AqJ+ibUFGAJ+d9kPH/Gi/t5+eV4F3mU/7boBsAAAAAElFTk' .

$data = base64decode($data);
$image = imagecreatefromstring($data);
imagepng($image, $path . '/image.png', 0);

// Up until this point, if you step debug you should
// be able to see the directory and files in it.
// Let us now clean up and remove everything.

// I'm going to use PHP's DirectoryIterator class
// If you're not familiar with it you should check it out
// It has some cool methods.
$tmp_files = new DirectoryIterator($path);
foreach($tmp_files as $file) {
    // I only created files, but there are a couple of 
    // directories that get in the way (i.e. '.' and '..')
    if($file->isFile()) {
        // So, if it's a file let's get rid of it
        unlink($path . $file->getBasename());
    // now remove the directory