FileHelper
- Type
- Class
- Namespace
- craft\helpers
- Inherits
- craft\helpers\FileHelper » yii\helpers\FileHelper » yii\helpers\BaseFileHelper
- Since
- 3.0.0
Class FileHelper
Public Properties
Property | Description |
---|---|
mimeAliasesFile | string – The path (or alias) of a PHP file containing MIME aliases. |
mimeExtensionsFile | string – The path (or alias) of a PHP file containing extensions per MIME type. |
mimeMagicFile | string – The path (or alias) of a PHP file containing MIME type information. |
mimeMagicFile
- Type
- string
- Default value
'@app/config/mimeTypes.php'
The path (or alias) of a PHP file containing MIME type information.
Public Methods
Method | Description |
---|---|
addFilesToZip() | Adds all the files in a given directory to a ZipArchive, preserving the nested directory structure. |
canTrustMimeType() | Returns whether a MIME type can be trusted, or whether we should double-check based on the file extension. |
changeOwnership() | Changes the Unix user and/or group ownership of a file or directory, and optionally the mode. |
clearDirectory() | Removes all of a directory’s contents recursively. |
copyDirectory() | Copies a whole directory as another one. |
createDirectory() | Creates a new directory. |
cycle() | Moves existing files down to *.1 , *.2 , etc. |
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. |
getExtensionByMimeType() | Return a file extension for the given MIME type. |
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. |
invalidate() | Invalidates a cached file with clearstatcache() and opcache_invalidate() . |
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. |
uniqueName() | Returns a unique version of a filename with uniqid() , ensuring the result is at most 255 characters. |
unlink() | Removes a file or symlink in a cross-platform way |
useFileLocks() | Returns whether file locks can be used when writing to files. |
writeGitignoreFile() | Creates a .gitignore file in the given directory if one doesn’t exist yet. |
writeToFile() | Writes contents to a file. |
zip() | Zips a file. |
addFilesToZip()
Adds all the files in a given directory to a ZipArchive, preserving the nested directory structure.
Arguments
$zip
(ZipArchive) – The ZipArchive object$dir
(string) – The directory path$prefix
(string, null) – The path prefix to use when adding the contents of the directory$options
(array) – Options for file searching. See findFiles() for available options.
canTrustMimeType()
- Since
- 3.1.7
Returns whether a MIME type can be trusted, or whether we should double-check based on the file extension.
Arguments
$mimeType
(string)
Returns
clearDirectory()
Removes all of a directory’s contents recursively.
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 tofalse
, 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
- yii\base\InvalidArgumentException
if the dir is invalid - yii\base\ErrorException
in case of failure
copyDirectory()
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
Arguments
$src
(string) – The source directory$dst
(string) – The destination directory$options
(array) – Options for directory copy. Valid options are:
Throws
- yii\base\InvalidArgumentException
if unable to open directory
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.
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)
cycle()
- Since
- 3.0.38
Moves existing files down to *.1
, *.2
, etc.
Arguments
$basePath
(string) – The base path to the first file (sans.X
)$max
(integer) – The most files that can coexist before we should start deleting them
getExtensionByMimeType()
- Since
- 3.5.15
Return a file extension for the given MIME type.
Arguments
$mimeType
(mixed
)$preferShort
(mixed
)$magicFile
(mixed
)
Returns
Throws
- yii\base\InvalidArgumentException
if no known extensions exist for the given MIME type.
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.
Arguments
$file
(string) – The file name.$magicFile
(string, null) – 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 thefileinfo
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 casefinfo_open()
cannot determine it.
Returns
string, null – The MIME type (e.g. text/plain
). Null is returned if the MIME type cannot be determined.
Throws
- yii\base\InvalidConfigException
when thefileinfo
PHP extension is not installed and$checkExtension
isfalse
.
hasAnythingChanged()
Returns whether any files in a source directory have changed, compared to another directory.
Arguments
Returns
Throws
- yii\base\InvalidArgumentException
if $dir or $ref isn't a directory - yii\base\ErrorException
if we can't get a handle on $src
invalidate()
- Since
- 3.4.0
Invalidates a cached file with clearstatcache()
and opcache_invalidate()
.
Arguments
$file
(string) – The file path
isDirectoryEmpty()
Returns whether a given directory is empty (has no files) recursively.
Arguments
$dir
(string) – The directory to be checked
Returns
boolean – Whether the directory is empty
Throws
- yii\base\InvalidArgumentException
if the dir is invalid - yii\base\ErrorException
in case of failure
isGif()
- Since
- 3.0.9
Returns whether the given file path is an GIF image.
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 thefileinfo
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 casefinfo_open()
cannot determine it.
Returns
isSvg()
Returns whether the given file path is an SVG image.
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 thefileinfo
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 casefinfo_open()
cannot determine it.
Returns
isWritable()
Tests whether a file/directory is writable.
Arguments
$path
(string) – The file/directory path to test
Returns
boolean – Whether the path is writable
Throws
- yii\base\ErrorException
in case of failure
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.
Arguments
$path
(string) – The directory to be checked
Returns
integer – Unix timestamp representing the last modification time
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")
Note: For registered stream wrappers, the consecutive slashes rule and ".."/"." translations are skipped.
Arguments
$path
(string) – The file/directory path to be normalized$ds
(string) – The directory separator to be used in the normalized result. Defaults toDIRECTORY_SEPARATOR
.
Returns
string – The normalized file/directory path
removeDirectory()
Removes a directory (and all its content) recursively.
Arguments
$dir
(string) – The directory to be deleted recursively.$options
(array) – Options for directory remove. Valid options are:
Throws
- yii\base\ErrorException
in case of failure
removeFile()
DEPRECATED
Deprecated in 3.0.0-RC11. Use unlink() instead.
Removes a file or symlink in a cross-platform way
Arguments
$path
(string) – The file to be deleted
Returns
sanitizeFilename()
Sanitizes a filename.
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
uniqueName()
- Since
- 3.8.3
Returns a unique version of a filename with uniqid()
, ensuring the result is at most 255 characters.
Arguments
$baseName
(string) – The original filename, or just a file extension prefixed with a.
.
Returns
unlink()
- Since
- 3.4.16
Removes a file or symlink in a cross-platform way
Arguments
$path
(string)
Returns
useFileLocks()
Returns whether file locks can be used when writing to files.
Returns
writeGitignoreFile()
- Since
- 3.4.0
Creates a .gitignore
file in the given directory if one doesn’t exist yet.
Arguments
$path
(string)$options
(array) – Options for file write. Valid options are:createDirs
: bool, whether to create parent directories if they do not exist. Defaults totrue
.lock
: bool, whether a file lock should be used. Defaults tofalse
.
Throws
- yii\base\InvalidArgumentException
if the parent directory doesn't exist andoptions[createDirs]
isfalse
- yii\base\Exception
if the parent directory can't be created - yii\base\ErrorException
in case of failure
writeToFile()
Writes contents to a file.
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 totrue
.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 theuseWriteFileLock
config setting.
Throws
- yii\base\InvalidArgumentException
if the parent directory doesn't exist andoptions[createDirs]
isfalse
- yii\base\Exception
if the parent directory can't be created - yii\base\ErrorException
in case of failure
zip()
- Since
- 3.5.0
Zips a file.
Arguments
$path
(string) – The file/directory path$to
(string, null) – The target zip file path. If null, the original path will be used, with “.zip” appended to it.
Returns
string – The zip file path
Throws
- yii\base\InvalidArgumentException
if$path
is not a valid file/directory path - yii\base\Exception
if the zip cannot be created
Protected Methods
Method | Description |
---|---|
loadMimeAliases() | Loads MIME aliases from the specified file. |
loadMimeExtensions() | Loads MIME extensions from the specified file. |
loadMimeTypes() | Loads MIME types from the specified file. |
normalizeOptions() |
Constants
Constant | Description |
---|---|
PATTERN_CASE_INSENSITIVE | |
PATTERN_ENDSWITH | |
PATTERN_MUSTBEDIR | |
PATTERN_NEGATIVE | |
PATTERN_NODIR |