FileHelper

Type
Class
Namespace
craft\helpers
Inherits
craft\helpers\FileHelper » yii\helpers\FileHelper » yii\helpers\BaseFileHelper
Since
3.0

Class FileHelper

View source

Public Properties

PropertyDescription
$mimeAliasesFilestring – The path (or alias) of a PHP file containing MIME aliases.
$mimeMagicFilestring – The path (or alias) of a PHP file containing MIME type information.

$mimeMagicFile

Type
string

The path (or alias) of a PHP file containing MIME type information.

View source

Signature

public static string $mimeMagicFile = '@app/config/mimeTypes.php'

Public Methods

MethodDescription
clearDirectory()Removes all of a directory’s contents recursively.
copyDirectory()Copies a whole directory as another one.
createDirectory()Creates a new directory.
filterPath()Checks if the given file path satisfies the filtering options.
findDirectories()Returns the directories found under the specified directory and subdirectories.
findFiles()Returns the files found under the specified directory and subdirectories.
getExtensionsByMimeType()Determines the extensions by given MIME type.
getMimeType()Determines the MIME type of the specified file.
getMimeTypeByExtension()Determines the MIME type based on the extension name of the specified file.
hasAnythingChanged()Returns whether any files in a source directory have changed, compared to another directory.
isDirectoryEmpty()Returns whether a given directory is empty (has no files) recursively.
isGif()Returns whether the given file path is an GIF image.
isSvg()Returns whether the given file path is an SVG image.
isWritable()Tests whether a file/directory is writable.
lastModifiedTime()Returns the last modification time for the given path.
localize()Returns the localized version of a specified file.
normalizePath()Normalizes a file/directory path.
removeDirectory()Removes a directory (and all its content) recursively.
removeFile()Removes a file or symlink in a cross-platform way
sanitizeFilename()Sanitizes a filename.
unlink()Removes a file or symlink in a cross-platform way
useFileLocks()Returns whether file locks can be used when writing to files.
writeToFile()Writes contents to a file.

clearDirectory()

Removes all of a directory’s contents recursively.

View source

Arguments

  • $dir (string) – The directory to be deleted recursively.
  • $options (array) – Options for directory remove. Valid options are:
  • traverseSymlinks: bool, whether symlinks to the directories should be traversed too. Defaults to false, meaning the content of the symlinked directory would not be deleted. Only symlink would be removed in that default case.
  • filter: callback (see findFiles())
  • except: array (see findFiles())
  • only: array (see findFiles())

Throws

Signature

public static void clearDirectory ( \craft\helpers\string $dir, array $options = [] )

copyDirectory()

Copies a whole directory as another one.

The files and sub-directories will also be copied over.

View source

Arguments

  • $src (string) – The source directory

  • $dst (string) – The destination directory

  • $options (array) – Options for directory copy. Valid options are:

  • dirMode: integer, the permission to be set for newly copied directories. Defaults to 0775.

  • fileMode: integer, the permission to be set for newly copied files. Defaults to the current environment setting.

  • filter: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: function ($path), where $path refers the full path to be filtered. The callback can return one of the following values:

    • true: the directory or file will be copied (the "only" and "except" options will be ignored)
    • false: the directory or file will NOT be copied (the "only" and "except" options will be ignored)
    • null: the "only" and "except" options will determine whether the directory or file should be copied
  • only: array, list of patterns that the file paths should match if they want to be copied. A path matches a pattern if it contains the pattern string at its end. For example, '.php' matches all file paths ending with '.php'. Note, the '/' characters in a pattern matches both '/' and '' in the paths. If a file path matches a pattern in both "only" and "except", it will NOT be copied.

  • except: array, list of patterns that the files or directories should match if they want to be excluded from being copied. A path matches a pattern if it contains the pattern string at its end. Patterns ending with '/' apply to directory paths only, and patterns not ending with '/' apply to file paths only. For example, '/a/b' matches all file paths ending with '/a/b'; and '.svn/' matches directory paths ending with '.svn'. Note, the '/' characters in a pattern matches both '/' and '' in the paths.

  • caseSensitive: boolean, whether patterns specified at "only" or "except" should be case sensitive. Defaults to true.

  • recursive: boolean, whether the files under the subdirectories should also be copied. Defaults to true.

  • beforeCopy: callback, a PHP callback that is called before copying each sub-directory or file. If the callback returns false, the copy operation for the sub-directory or file will be cancelled. The signature of the callback should be: function ($from, $to), where $from is the sub-directory or file to be copied from, while $to is the copy target.

  • afterCopy: callback, a PHP callback that is called after each sub-directory or file is successfully copied. The signature of the callback should be: function ($from, $to), where $from is the sub-directory or file copied from, while $to is the copy target.

  • copyEmptyDirectories: boolean, whether to copy empty directories. Set this to false to avoid creating directories that do not contain files. This affects directories that do not contain files initially as well as directories that do not contain files at the target destination because files have been filtered via only or except. Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.

Throws

Signature

public static void copyDirectory ( $src, $dst, $options = [] )

createDirectory()

Creates a new directory.

This method is similar to the PHP mkdir() function except that it uses chmod() to set the permission of the created directory in order to avoid the impact of the umask setting.

View source

Arguments

  • $path (string) – Path of the directory to be created.
  • $mode (integer) – The permission to be set for the created directory.
  • $recursive (boolean) – Whether to create parent directories if they do not exist.

Returns

boolean – Whether the directory is created successfully

Throws

  • yii\base\Exception
    if the directory could not be created (i.e. php error due to parallel changes)

Signature

public static boolean createDirectory ( $path, $mode = null, $recursive = true )

getMimeType()

Determines the MIME type of the specified file.

This method will first try to determine the MIME type based on finfo_open. If the fileinfo extension is not installed, it will fall back to getMimeTypeByExtension() when $checkExtension is true.

View source

Arguments

  • $file (string) – The file name.
  • $magicFile (string) – Name of the optional magic database file (or alias), usually something like /path/to/magic.mime. This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
  • $checkExtension (boolean) – Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.

Returns

string – The MIME type (e.g. text/plain). Null is returned if the MIME type cannot be determined.

Throws

Signature

public static string getMimeType ( $file, $magicFile = null, $checkExtension = true )

hasAnythingChanged()

Returns whether any files in a source directory have changed, compared to another directory.

View source

Arguments

  • $dir (string) – The source directory to check for changes in
  • $ref (string) – The reference directory

Returns

boolean

Throws

Signature

public static boolean hasAnythingChanged ( \craft\helpers\string $dir, \craft\helpers\string $ref )

isDirectoryEmpty()

Returns whether a given directory is empty (has no files) recursively.

View source

Arguments

  • $dir (string) – The directory to be checked

Returns

boolean – Whether the directory is empty

Throws

Signature

public static boolean isDirectoryEmpty ( \craft\helpers\string $dir )

isGif()

Returns whether the given file path is an GIF image.

View source

Arguments

  • $file (string) – The file name.
  • $magicFile (string) – Name of the optional magic database file (or alias), usually something like /path/to/magic.mime. This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
  • $checkExtension (boolean) – Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.

Returns

boolean

Signature

public static boolean isGif ( \craft\helpers\string $file, \craft\helpers\string $magicFile = null, \craft\helpers\bool $checkExtension = true )

isSvg()

Returns whether the given file path is an SVG image.

View source

Arguments

  • $file (string) – The file name.
  • $magicFile (string) – Name of the optional magic database file (or alias), usually something like /path/to/magic.mime. This will be passed as the second parameter to finfo_open() when the fileinfo extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() and this is null, it will use the file specified by $mimeMagicFile.
  • $checkExtension (boolean) – Whether to use the file extension to determine the MIME type in case finfo_open() cannot determine it.

Returns

boolean

Signature

public static boolean isSvg ( \craft\helpers\string $file, \craft\helpers\string $magicFile = null, \craft\helpers\bool $checkExtension = true )

isWritable()

Tests whether a file/directory is writable.

View source

Arguments

  • $path (string) – The file/directory path to test

Returns

boolean – Whether the path is writable

Throws

Signature

public static boolean isWritable ( \craft\helpers\string $path )

lastModifiedTime()

Returns the last modification time for the given path. If the path is a directory, any nested files/directories will be checked as well.

View source

Arguments

  • $path (string) – The directory to be checked

Returns

integer – Unix timestamp representing the last modification time

Signature

public static integer lastModifiedTime ( $path )

normalizePath()

Normalizes a file/directory path.

The normalization does the following work:

  • Convert all directory separators into DIRECTORY_SEPARATOR (e.g. "\a/b\c" becomes "/a/b/c")
  • Remove trailing directory separators (e.g. "/a/b/c/" becomes "/a/b/c")
  • Turn multiple consecutive slashes into a single one (e.g. "/a///b/c" becomes "/a/b/c")
  • Remove ".." and "." based on their meanings (e.g. "/a/./b/../c" becomes "/a/c")

View source

Arguments

  • $path (string) – The file/directory path to be normalized
  • $ds (string) – The directory separator to be used in the normalized result. Defaults to DIRECTORY_SEPARATOR.

Returns

string – The normalized file/directory path

Signature

public static string normalizePath ( $path, $ds = DIRECTORY_SEPARATOR )

removeDirectory()

Removes a directory (and all its content) recursively.

View source

Arguments

  • $dir (string) – The directory to be deleted recursively.

  • $options (array) – Options for directory remove. Valid options are:

  • traverseSymlinks: boolean, whether symlinks to the directories should be traversed too. Defaults to false, meaning the content of the symlinked directory would not be deleted. Only symlink would be removed in that default case.

Throws

Signature

public static void removeDirectory ( $dir, $options = [] )

removeFile()

DEPRECATED

Deprecated in 3.0.0-RC11. Use unlink() instead.

Removes a file or symlink in a cross-platform way

View source

Arguments

  • $path (string) – The file to be deleted

Returns

boolean

Signature

public static boolean removeFile ( \craft\helpers\string $path )

sanitizeFilename()

Sanitizes a filename.

View source

Arguments

  • $filename (string) – The filename to sanitize
  • $options (array) – Options for sanitization. Valid options are:
  • asciiOnly: bool, whether only ASCII characters should be allowed. Defaults to false.
  • separator: string|null, the separator character to use in place of whitespace. defaults to '-'. If set to null, whitespace will be preserved.

Returns

string – The cleansed filename

Signature

public static string sanitizeFilename ( \craft\helpers\string $filename, array $options = [] )

useFileLocks()

Returns whether file locks can be used when writing to files.

View source

Returns

boolean

Signature

public static boolean useFileLocks ( )

writeToFile()

Writes contents to a file.

View source

Arguments

  • $file (string) – The file path
  • $contents (string) – The new file contents
  • $options (array) – Options for file write. Valid options are:
  • createDirs: bool, whether to create parent directories if they do not exist. Defaults to true.
  • append: bool, whether the contents should be appended to the existing contents. Defaults to false.
  • lock: bool, whether a file lock should be used. Defaults to the "useWriteFileLock" config setting.

Throws

Signature

public static void writeToFile ( \craft\helpers\string $file, \craft\helpers\string $contents, array $options = [] )

Protected Methods

MethodDescription
loadMimeAliases()Loads MIME aliases from the specified file.
loadMimeTypes()Loads MIME types from the specified file.
normalizeOptions()

Constants

ConstantDescription
PATTERN_CASE_INSENSITIVE
PATTERN_ENDSWITH
PATTERN_MUSTBEDIR
PATTERN_NEGATIVE
PATTERN_NODIR