PHP 轻松的文件夹结构设置

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PHP 轻松的文件夹结构设置相关的知识,希望对你有一定的参考价值。

<?php

/**
 * Recursive function for creating folder structures
 * @param   string   Path to directory where $dir_structure should start creating dirs
 * @param   array    Associative array describing directory structure.
 * @param   integer  Optional file mode to create and check folders for. Defaults to 0755
 */
function create_folder_structure($base_path, $structure, $file_mode = 0755)
{
  foreach ($structure as $key => $value)
  {
    if (!file_exists($base_path))
      throw new Exception(sprintf('Directory "%s" does not exist', $base_path));
      
    // value can be either the directory name or an array containing deeper directory structure
    $dir_name = is_string($key) ? $key : $value;
    $path_to_dir = $base_path.'/'.$dir_name;
    
    // create directory or set permissions
    if (!file_exists($path_to_dir))
      mkdir($path_to_dir, $file_mode);
    else
      chmod($path_to_dir, $file_mode);
    
    if (!file_exists($path_to_dir) || !is_readable($path_to_dir) || !is_writeable($path_to_dir))
      throw new Exception(sprintf('Cannot create or set file mode for directory "%s" to %d', $path_to_dir, $file_mode));
    
    // create any deeper directory structure recursively
    if (is_array($value))
      create_folder_structure($path_to_dir, $value, $file_mode);
  }
}

/**
 * Example
 * Creates a folder structure in the already existing folder 'storage'
 * The folder structure will look like this:
 * storage/
 * storage/images/
 * storage/images/thumbnails/
 * storage/images/thumbnails/large/
 * storage/images/thumbnails/small/
 * storage/images/portraits/
 * storage/favorites/
 * storage/tmp/
 * storage/tmp/uploads/
 * storage/tmp/edit/
 * storage/files/
 *
 * All of the folders will have file mode 0755. Pretty simple right?
 */

$arr_structure = array
  (
  'images' => array
    (
    'thumbnails' => array
      (
      'large',
      'small'
      ),
    'portraits'
    ),
  'favorites',
  'tmp' => array
    (
    'uploads',
    'edit'
    ),
  'files'
  );
try
{
  create_folder_structure('storage', $arr_structure);
}
catch (Exception $e)
{
  print $e->getMessage();
}

?>

以上是关于PHP 轻松的文件夹结构设置的主要内容,如果未能解决你的问题,请参考以下文章

使用jQuery/AJAX/PHP轻松设置验证码

apache 如何设置能实现:正常浏览目录结构(包括虚拟目录)和下载文件,但又禁止PHP,ASP==的运行?

PHP 轻松调试变量,以查找tpl.php文件中可用的变量

PHP中目录结构的深度递归数组

PECL轻松安装PHP扩展

如何轻松地在 PHP 中缩小 JS ......或其他