Our blog

 

PHP: Recursive Create Path (if not exists)

Handling directories and files with PHP is a snap. However, with this handy function you can always be sure that the destination directory path for your files will exist.

If you pass a path with a filename at teh end, set the second parameter to true eg make_path($path, true)

PHP:
  1. /*Create  Directory Tree if Not Exists
  2. If you are passing a path with a filename on the end, pass true as the second parameter to snip it off */
  3. function make_path($pathname, $is_filename=false){
  4.  
  5.     if($is_filename){
  6.  
  7.         $pathname = substr($pathname, 0, strrpos($pathname, '/'));
  8.  
  9.     }
  10.  
  11.     // Check if directory already exists
  12.  
  13.     if (is_dir($pathname) || empty($pathname)) {
  14.  
  15.         return true;
  16.  
  17.     }
  18.  
  19.     // Ensure a file does not already exist with the same name
  20.  
  21.     $pathname = str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $pathname);
  22.  
  23.     if (is_file($pathname)) {
  24.  
  25.         trigger_error('mkdirr() File exists', E_USER_WARNING);
  26.  
  27.         return false;
  28.  
  29.     }
  30.  
  31.     // Crawl up the directory tree
  32.  
  33.     $next_pathname = substr($pathname, 0, strrpos($pathname, DIRECTORY_SEPARATOR));
  34.  
  35.     if (make_path($next_pathname, $mode)) {
  36.  
  37.         if (!file_exists($pathname)) {
  38.  
  39.             return mkdir($pathname, $mode);
  40.  
  41.         }
  42.  
  43.     }
  44.  
  45.     return false;
  46.  
  47. }

More Reading:

  • no matching posts found..

 

Leave a Reply