Friday, March 4, 2011

How to create nested directory using php?

In php mkdir() we can easily create a diretory , here i am going to explain how to create a nested directory using simple php script


<?php
$folder_path = 'tmp/downlaod/2011';
if (!$folder_path) {
    echo 'invalid path name!';
    exit;
}

if (file_exists("/temp/download")) {
  echo "Directory exists.\n";
  exit;
}
$folders = explode('/',$folder_path);
$tmp_path = '';
foreach ($folders as $key=>$name) {
    $tmp_path.=$name;
    if (!file_exists($tmp_path)) {
        mkdir($tmp_path,777);   
    }
    $tmp_path.=DIRECTORY_SEPARATOR;
}
?>

using this you can easily create nested directory .



2 comments:

  1. mkdir() has a second parameter

    +recursive: Allows the creation of nested directories specified in the pathname. Defaults to FALSE.

    $path = '/path/to/folder/with/subdirectory';
    mkdir($path, 0777, true);

    Details: http://stackoverflow.com/questions/6579936/php-create-nested-directories

    ReplyDelete