FileHelper
- Type
- Class
- Namespace
- craft\helpers
- Inherits
- craft\helpers\FileHelper » yii\helpers\FileHelper (opens new window) » yii\helpers\BaseFileHelper (opens new window)
- Since
- 3.0.0
Class FileHelper
View source (opens new window)
# Public Properties
Property | Description |
---|---|
mimeAliasesFile (opens new window) | string (opens new window) – The path (or alias) of a PHP file containing MIME aliases. |
mimeExtensionsFile (opens new window) | string (opens new window) – The path (or alias) of a PHP file containing extensions per MIME type. |
mimeMagicFile | string (opens new window) – The path (or alias) of a PHP file containing MIME type information. |
# mimeMagicFile
- Type
- string (opens new window)
- Default value
'@app/config/mimeTypes.php'
The path (or alias) of a PHP file containing MIME type information.
View source (opens new window)
# Public Methods
Method | Description |
---|---|
absolutePath() | Returns an absolute path based on a source location or the current working directory. |
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() (opens new window) | 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. |
deleteFileAfterRequest() | Deletes a file after the request ends. |
deleteQueuedFiles() | Delete all files queued up for deletion. |
filterPath() (opens new window) | Checks if the given file path satisfies the filtering options. |
findClosestFile() | Traverses up the filesystem looking for the closest file to the given directory. |
findDirectories() (opens new window) | Returns the directories found under the specified directory and subdirectories. |
findFiles() (opens new window) | Returns the files found under the specified directory and subdirectories. |
getExtensionByMimeType() | Return a file extension for the given MIME type. |
getExtensionsByMimeType() (opens new window) | Determines the extensions by given MIME type. |
getMimeType() | Determines the MIME type of the specified file. |
getMimeTypeByExtension() (opens new window) | 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. |
isWithin() | Returns whether the given path is within another path. |
isWritable() | Tests whether a file/directory is writable. |
lastModifiedTime() | Returns the last modification time for the given path. |
localize() (opens new window) | Returns the localized version of a specified file. |
normalizePath() | Normalizes a file/directory path. |
relativePath() | Returns a relative path based on a source location or the current working directory. |
removeDirectory() | Removes a directory (and all its content) recursively. |
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. |
# absolutePath()
- Since
- 4.3.5
Returns an absolute path based on a source location or the current working directory.
View source (opens new window)
Arguments
$to
(string (opens new window)) – The target path.$from
(string (opens new window), null (opens new window)) – The source location. Defaults to the current working directory.$ds
(string (opens new window)) – The directory separator to be used in the normalized result. Defaults toDIRECTORY_SEPARATOR
.
Returns
# addFilesToZip()
- Since
- 3.5.0
Adds all the files in a given directory to a ZipArchive, preserving the nested directory structure.
View source (opens new window)
Arguments
$zip
(ZipArchive (opens new window)) – The ZipArchive object$dir
(string (opens new window)) – The directory path$prefix
(string (opens new window), null (opens new window)) – The path prefix to use when adding the contents of the directory$options
(array (opens new window)) – Options for file searching. See findFiles() (opens new window) 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.
View source (opens new window)
Arguments
$mimeType
(string (opens new window))
Returns
# clearDirectory()
Removes all of a directory’s contents recursively.
View source (opens new window)
Arguments
$dir
(string (opens new window)) – The directory to be deleted recursively.$options
(array (opens new window)) – 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() (opens new window))except
: array (see findFiles() (opens new window))only
: array (see findFiles() (opens new window))
Throws
- yii\base\InvalidArgumentException (opens new window)
if the dir is invalid - yii\base\ErrorException (opens new window)
in case of failure
# copyDirectory()
Copies a whole directory as another one.
The files and sub-directories will also be copied over.
View source (opens new window)
Arguments
$src
(string (opens new window)) – The source directory$dst
(string (opens new window)) – The destination directory$options
(array (opens new window)) – 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
orexcept
. Defaults to true. This option is available since version 2.0.12. Before 2.0.12 empty directories are always copied.
Throws
- yii\base\InvalidArgumentException (opens new window)
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.
View source (opens new window)
Arguments
$path
(string (opens new window)) – Path of the directory to be created.$mode
(integer (opens new window)) – The permission to be set for the created directory.$recursive
(boolean (opens new window)) – Whether to create parent directories if they do not exist.
Returns
boolean (opens new window) – Whether the directory is created successfully
Throws
- yii\base\Exception (opens new window)
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.
View source (opens new window)
Arguments
$basePath
(string (opens new window)) – The base path to the first file (sans.X
)$max
(integer (opens new window)) – The most files that can coexist before we should start deleting them
# deleteFileAfterRequest()
- Since
- 4.0.0
Deletes a file after the request ends.
View source (opens new window)
Arguments
$filename
(string (opens new window))
# deleteQueuedFiles()
- Since
- 4.0.0
Delete all files queued up for deletion.
View source (opens new window)
# findClosestFile()
- Since
- 4.3.5
Traverses up the filesystem looking for the closest file to the given directory.
View source (opens new window)
Arguments
$dir
(string (opens new window)) – The directory at or above which the file will be looked for$options
(array (opens new window)) – Options for file searching. See findFiles() (opens new window).
Returns
string (opens new window), null (opens new window) – The closest matching file
Throws
- yii\base\InvalidArgumentException (opens new window)
if the directory is invalid
# getExtensionByMimeType()
- Since
- 3.5.15
Return a file extension for the given MIME type.
View source (opens new window)
Arguments
$mimeType
(string (opens new window))$preferShort
(boolean (opens new window))$magicFile
(string (opens new window), null (opens new window))
Returns
Throws
- yii\base\InvalidArgumentException (opens new window)
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 (opens new window). If the fileinfo
extension is not installed,
it will fall back to getMimeTypeByExtension() (opens new window) when $checkExtension
is true.
View source (opens new window)
Arguments
$file
(string (opens new window)) – The file name.$magicFile
(string (opens new window), null (opens new window)) – 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() (opens new window) when thefileinfo
extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() (opens new window) and this is null, it will use the file specified by mimeMagicFile.$checkExtension
(boolean (opens new window)) – Whether to use the file extension to determine the MIME type in casefinfo_open()
cannot determine it.
Returns
string (opens new window), null (opens new window) – The MIME type (e.g. text/plain
). Null is returned if the MIME type cannot be determined.
Throws
- yii\base\InvalidConfigException (opens new window)
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.
View source (opens new window)
Arguments
$dir
(string (opens new window)) – The source directory to check for changes in$ref
(string (opens new window)) – The reference directory
Returns
Throws
- yii\base\InvalidArgumentException (opens new window)
if $dir or $ref isn't a directory - yii\base\ErrorException (opens new window)
if we can't get a handle on $src
# invalidate()
- Since
- 3.4.0
Invalidates a cached file with clearstatcache()
and opcache_invalidate()
.
View source (opens new window)
Arguments
$file
(string (opens new window)) – The file path
# isDirectoryEmpty()
Returns whether a given directory is empty (has no files) recursively.
View source (opens new window)
Arguments
$dir
(string (opens new window)) – The directory to be checked
Returns
boolean (opens new window) – Whether the directory is empty
Throws
- yii\base\InvalidArgumentException (opens new window)
if the dir is invalid - yii\base\ErrorException (opens new window)
in case of failure
# isGif()
- Since
- 3.0.9
Returns whether the given file path is an GIF image.
View source (opens new window)
Arguments
$file
(string (opens new window)) – The file name.$magicFile
(string (opens new window), null (opens new window)) – 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() (opens new window) when thefileinfo
extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() (opens new window) and this is null, it will use the file specified by mimeMagicFile.$checkExtension
(boolean (opens new window)) – 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.
View source (opens new window)
Arguments
$file
(string (opens new window)) – The file name.$magicFile
(string (opens new window), null (opens new window)) – 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() (opens new window) when thefileinfo
extension is installed. If the MIME type is being determined based via getMimeTypeByExtension() (opens new window) and this is null, it will use the file specified by mimeMagicFile.$checkExtension
(boolean (opens new window)) – Whether to use the file extension to determine the MIME type in casefinfo_open()
cannot determine it.
Returns
# isWithin()
Returns whether the given path is within another path.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The path to check$parentPath
(string (opens new window)) – The parent path that$path
should be within
Returns
# isWritable()
Tests whether a file/directory is writable.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The file/directory path to test
Returns
boolean (opens new window) – Whether the path is writable
Throws
- yii\base\ErrorException (opens new window)
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.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The directory to be checked
Returns
integer (opens new window) – 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.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The file/directory path to be normalized$ds
(string (opens new window)) – The directory separator to be used in the normalized result. Defaults toDIRECTORY_SEPARATOR
.
Returns
string (opens new window) – The normalized file/directory path
# relativePath()
- Since
- 4.3.5
Returns a relative path based on a source location or the current working directory.
View source (opens new window)
Arguments
$to
(string (opens new window)) – The target path.$from
(string (opens new window), null (opens new window)) – The source location. Defaults to the current working directory.$ds
(string (opens new window)) – The directory separator to be used in the normalized result. Defaults toDIRECTORY_SEPARATOR
.
Returns
string (opens new window) – The relative path if possible, or an absolute path if the directory is not contained within $from
.
# removeDirectory()
Removes a directory (and all its content) recursively.
View source (opens new window)
Arguments
$dir
(string (opens new window)) – The directory to be deleted recursively.$options
(array (opens new window)) – 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
- yii\base\ErrorException (opens new window)
in case of failure
# sanitizeFilename()
Sanitizes a filename.
View source (opens new window)
Arguments
$filename
(string (opens new window)) – The filename to sanitize$options
(array (opens new window)) – 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 (opens new window) – The cleansed filename
# uniqueName()
- Since
- 4.4.3
Returns a unique version of a filename with uniqid()
, ensuring the result is at most 255 characters.
View source (opens new window)
Arguments
$baseName
(string (opens new window)) – 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
View source (opens new window)
Arguments
$path
(string (opens new window))
Returns
# useFileLocks()
Returns whether file locks can be used when writing to files.
View source (opens new window)
Returns
# writeGitignoreFile()
- Since
- 3.4.0
Creates a .gitignore
file in the given directory if one doesn’t exist yet.
View source (opens new window)
Arguments
$path
(string (opens new window))$options
(array (opens new window)) – 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 (opens new window)
if the parent directory doesn't exist andoptions[createDirs]
isfalse
- yii\base\Exception (opens new window)
if the parent directory can't be created - yii\base\ErrorException (opens new window)
in case of failure
# writeToFile()
Writes contents to a file.
View source (opens new window)
Arguments
$file
(string (opens new window)) – The file path$contents
(string (opens new window)) – The new file contents$options
(array (opens new window)) – 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 (opens new window)
if the parent directory doesn't exist andoptions[createDirs]
isfalse
- yii\base\Exception (opens new window)
if the parent directory can't be created - yii\base\ErrorException (opens new window)
in case of failure
# zip()
- Since
- 3.5.0
Zips a file.
View source (opens new window)
Arguments
$path
(string (opens new window)) – The file/directory path$to
(string (opens new window), null (opens new window)) – The target zip file path. If null, the original path will be used, with “.zip” appended to it.
Returns
string (opens new window) – The zip file path
Throws
- yii\base\InvalidArgumentException (opens new window)
if$path
is not a valid file/directory path - yii\base\Exception (opens new window)
if the zip cannot be created
# Protected Methods
Method | Description |
---|---|
loadMimeAliases() (opens new window) | Loads MIME aliases from the specified file. |
loadMimeExtensions() (opens new window) | Loads MIME extensions from the specified file. |
loadMimeTypes() (opens new window) | Loads MIME types from the specified file. |
normalizeOptions() (opens new window) |
# Constants
Constant | Description |
---|---|
PATTERN_CASE_INSENSITIVE | |
PATTERN_ENDSWITH | |
PATTERN_MUSTBEDIR | |
PATTERN_NEGATIVE | |
PATTERN_NODIR |
← FieldHelper Gql →