Versions
Look up a class, method, property or event

CFileHelper

Package system.utils
Inheritance class CFileHelper
Since 1.0
Source Code framework/utils/CFileHelper.php
CFileHelper provides a set of helper methods for common file system operations.

Public Methods

Hide inherited methods

MethodDescriptionDefined By
copyDirectory() Copies a directory recursively as another. CFileHelper
findFiles() Returns the files found under the specified directory and subdirectories. CFileHelper
getExtension() Returns the extension name of a file path. CFileHelper
getMimeType() Determines the MIME type of the specified file. CFileHelper
getMimeTypeByExtension() Determines the MIME type based on the extension name of the specified file. CFileHelper
removeDirectory() Removes a directory recursively. CFileHelper

Protected Methods

Hide inherited methods

MethodDescriptionDefined By
copyDirectoryRecursive() Copies a directory. CFileHelper
findFilesRecursive() Returns the files found under the specified directory and subdirectories. CFileHelper
validatePath() Validates a file or directory. CFileHelper

Method Details

copyDirectory() method
public static void copyDirectory(string $src, string $dst, array $options=array ( ))
$src string the source directory
$dst string the destination directory
$options array options for directory copy. Valid options are:
  • fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be copied.
  • exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
  • level: integer, recursion depth, default=-1. Level -1 means copying all directories and files under the directory; Level 0 means copying only the files DIRECTLY under the directory; level N means copying those directories that are within N levels.
  • newDirMode - the permission to be set for newly copied directories (defaults to 0777);
  • newFileMode - the permission to be set for newly copied files (defaults to the current environment setting).
Source Code: framework/utils/CFileHelper.php#54 (show)
public static function copyDirectory($src,$dst,$options=array())
{
    
$fileTypes=array();
    
$exclude=array();
    
$level=-1;
    
extract($options);
    if(!
is_dir($dst))
        
self::mkdir($dst,$options,true);

    
self::copyDirectoryRecursive($src,$dst,'',$fileTypes,$exclude,$level,$options);
}

Copies a directory recursively as another. If the destination directory does not exist, it will be created recursively.

copyDirectoryRecursive() method
protected static void copyDirectoryRecursive(string $src, string $dst, string $base, array $fileTypes, array $exclude, integer $level, array $options)
$src string the source directory
$dst string the destination directory
$base string the path relative to the original source directory
$fileTypes array list of file name suffix (without dot). Only files with these suffixes will be copied.
$exclude array list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
$level integer recursion depth. It defaults to -1. Level -1 means copying all directories and files under the directory; Level 0 means copying only the files DIRECTLY under the directory; level N means copying those directories that are within N levels.
$options array additional options. The following options are supported: newDirMode - the permission to be set for newly copied directories (defaults to 0777); newFileMode - the permission to be set for newly copied files (defaults to the current environment setting).
Source Code: framework/utils/CFileHelper.php#136 (show)
protected static function copyDirectoryRecursive($src,$dst,$base,$fileTypes,$exclude,$level,$options)
{
    if(!
is_dir($dst))
        
self::mkdir($dst,$options,false);

    
$folder=opendir($src);
    while((
$file=readdir($folder))!==false)
    {
        if(
$file==='.' || $file==='..')
            continue;
        
$path=$src.DIRECTORY_SEPARATOR.$file;
        
$isFile=is_file($path);
        if(
self::validatePath($base,$file,$isFile,$fileTypes,$exclude))
        {
            if(
$isFile)
            {
                
copy($path,$dst.DIRECTORY_SEPARATOR.$file);
                if(isset(
$options['newFileMode']))
                    @
chmod($dst.DIRECTORY_SEPARATOR.$file,$options['newFileMode']);
            }
            elseif(
$level)
                
self::copyDirectoryRecursive($path,$dst.DIRECTORY_SEPARATOR.$file,$base.'/'.$file,$fileTypes,$exclude,$level-1,$options);
        }
    }
    
closedir($folder);
}

Copies a directory. This method is mainly used by copyDirectory.

findFiles() method
public static array findFiles(string $dir, array $options=array ( ))
$dir string the directory under which the files will be looked for
$options array options for file searching. Valid options are:
  • fileTypes: array, list of file name suffix (without dot). Only files with these suffixes will be returned.
  • exclude: array, list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
  • level: integer, recursion depth, default=-1. Level -1 means searching for all directories and files under the directory; Level 0 means searching for only the files DIRECTLY under the directory; level N means searching for those directories that are within N levels.
{return} array files found under the directory. The file list is sorted.
Source Code: framework/utils/CFileHelper.php#106 (show)
public static function findFiles($dir,$options=array())
{
    
$fileTypes=array();
    
$exclude=array();
    
$level=-1;
    
extract($options);
    
$list=self::findFilesRecursive($dir,'',$fileTypes,$exclude,$level);
    
sort($list);
    return 
$list;
}

Returns the files found under the specified directory and subdirectories.

findFilesRecursive() method
protected static array findFilesRecursive(string $dir, string $base, array $fileTypes, array $exclude, integer $level)
$dir string the source directory
$base string the path relative to the original source directory
$fileTypes array list of file name suffix (without dot). Only files with these suffixes will be returned.
$exclude array list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, it will not be copied. For example, an exclusion of '.svn' will exclude all files and directories whose name is '.svn'. And an exclusion of '/a/b' will exclude file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
$level integer recursion depth. It defaults to -1. Level -1 means searching for all directories and files under the directory; Level 0 means searching for only the files DIRECTLY under the directory; level N means searching for those directories that are within N levels.
{return} array files found under the directory.
Source Code: framework/utils/CFileHelper.php#179 (show)
protected static function findFilesRecursive($dir,$base,$fileTypes,$exclude,$level)
{
    
$list=array();
    
$handle=opendir($dir);
    while((
$file=readdir($handle))!==false)
    {
        if(
$file==='.' || $file==='..')
            continue;
        
$path=$dir.DIRECTORY_SEPARATOR.$file;
        
$isFile=is_file($path);
        if(
self::validatePath($base,$file,$isFile,$fileTypes,$exclude))
        {
            if(
$isFile)
                
$list[]=$path;
            elseif(
$level)
                
$list=array_merge($list,self::findFilesRecursive($path,$base.'/'.$file,$fileTypes,$exclude,$level-1));
        }
    }
    
closedir($handle);
    return 
$list;
}

Returns the files found under the specified directory and subdirectories. This method is mainly used by findFiles.

getExtension() method (available since v1.1.2)
public static string getExtension(string $path)
$path string the file path
{return} string the extension name without the dot character.
Source Code: framework/utils/CFileHelper.php#27 (show)
public static function getExtension($path)
{
    return 
pathinfo($path,PATHINFO_EXTENSION);
}

Returns the extension name of a file path. For example, the path "path/to/something.php" would return "php".

getMimeType() method
public static string getMimeType(string $file, string $magicFile=NULL, boolean $checkExtension=true)
$file string the file name.
$magicFile string name of a magic database file, usually something like /path/to/magic.mime. This will be passed as the second parameter to finfo_open. Magic file format described in man 5 magic, note that this file does not contain a standard PHP array as you might suppose. Specified magic file will be used only when fileinfo PHP extension is available. This parameter has been available since version 1.1.3.
$checkExtension boolean whether to check the file extension in case the MIME type cannot be determined based on finfo and mime_content_type. Defaults to true. This parameter has been available since version 1.1.4.
{return} string the MIME type. Null is returned if the MIME type cannot be determined.
Source Code: framework/utils/CFileHelper.php#246 (show)
public static function getMimeType($file,$magicFile=null,$checkExtension=true)
{
    if(
function_exists('finfo_open'))
    {
        
$options=defined('FILEINFO_MIME_TYPE') ? FILEINFO_MIME_TYPE FILEINFO_MIME;
        
$info=$magicFile===null finfo_open($options) : finfo_open($options,$magicFile);

        if(
$info && ($result=finfo_file($info,$file))!==false)
            return 
$result;
    }

    if(
function_exists('mime_content_type') && ($result=mime_content_type($file))!==false)
        return 
$result;

    return 
$checkExtension self::getMimeTypeByExtension($file) : null;
}

Determines the MIME type of the specified file. This method will attempt the following approaches in order:

  1. finfo
  2. mime_content_type
  3. getMimeTypeByExtension, when $checkExtension is set true.

getMimeTypeByExtension() method
public static string getMimeTypeByExtension(string $file, string $magicFile=NULL)
$file string the file name.
$magicFile string the path of the file that contains all available MIME type information. If this is not set, the default 'system.utils.mimeTypes' file will be used. This parameter has been available since version 1.1.3.
{return} string the MIME type. Null is returned if the MIME type cannot be determined.
Source Code: framework/utils/CFileHelper.php#272 (show)
public static function getMimeTypeByExtension($file,$magicFile=null)
{
    static 
$extensions,$customExtensions=array();
    if(
$magicFile===null && $extensions===null)
        
$extensions=require(Yii::getPathOfAlias('system.utils.mimeTypes').'.php');
    elseif(
$magicFile!==null && !isset($customExtensions[$magicFile]))
        
$customExtensions[$magicFile]=require($magicFile);
    if((
$ext=pathinfo($file,PATHINFO_EXTENSION))!=='')
    {
        
$ext=strtolower($ext);
        if(
$magicFile===null && isset($extensions[$ext]))
            return 
$extensions[$ext];
        elseif(
$magicFile!==null && isset($customExtensions[$magicFile][$ext]))
            return 
$customExtensions[$magicFile][$ext];
    }
    return 
null;
}

Determines the MIME type based on the extension name of the specified file. This method will use a local map between extension name and MIME type.

removeDirectory() method (available since v1.1.14)
public static void removeDirectory(string $directory)
$directory string to be deleted recursively.
Source Code: framework/utils/CFileHelper.php#71 (show)
public static function removeDirectory($directory)
{
    
$items=glob($directory.DIRECTORY_SEPARATOR.'{,.}*',GLOB_MARK GLOB_BRACE);
    foreach(
$items as $item)
    {
        if(
basename($item)=='.' || basename($item)=='..')
            continue;
        if(
substr($item,-1)==DIRECTORY_SEPARATOR)
            
self::removeDirectory($item);
        else
            
unlink($item);
    }
    if(
is_dir($directory))
        
rmdir($directory);
}

Removes a directory recursively.

validatePath() method
protected static boolean validatePath(string $base, string $file, boolean $isFile, array $fileTypes, array $exclude)
$base string the path relative to the original source directory
$file string the file or directory name
$isFile boolean whether this is a file
$fileTypes array list of valid file name suffixes (without dot).
$exclude array list of directory and file exclusions. Each exclusion can be either a name or a path. If a file or directory name or path matches the exclusion, false will be returned. For example, an exclusion of '.svn' will return false for all files and directories whose name is '.svn'. And an exclusion of '/a/b' will return false for file or directory '$src/a/b'. Note, that '/' should be used as separator regardless of the value of the DIRECTORY_SEPARATOR constant.
{return} boolean whether the file or directory is valid
Source Code: framework/utils/CFileHelper.php#213 (show)
protected static function validatePath($base,$file,$isFile,$fileTypes,$exclude)
{
    foreach(
$exclude as $e)
    {
        if(
$file===$e || strpos($base.'/'.$file,$e)===0)
            return 
false;
    }
    if(!
$isFile || empty($fileTypes))
        return 
true;
    if((
$type=pathinfo($file,PATHINFO_EXTENSION))!=='')
        return 
in_array($type,$fileTypes);
    else
        return 
false;
}

Validates a file or directory.

Total 1 comment

#2132 report it
Mike at 2010/11/16 09:19am
getMimeType() is incompatible with pecl/fileinfo for PHP < 5.3.0

Before PHP 5.3.0 the pecl extension fileinfo provided the same set of methods that is used to find out the mime type. Problem is, that the constant FILEINFO_MIME_TYPE did not exist in that extension (it was introduced in PHP 5.3.0). So if you have pecl-fileinfo installed and call CFileHelper::getMimeType() you'll receive an error.

Leave a comment

Please to leave your comment.