# BaseFileHelper

> BaseFileHelper provides concrete implementation for yii\helpers\FileHelper.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [helpers](/docs/api/yii/helpers/index.md) › BaseFileHelper

| class | `yii\helpers\BaseFileHelper` |
| --- | --- |
| Since | 2.0 |
| Source | [`framework/helpers/BaseFileHelper.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/helpers/BaseFileHelper.php#L26) |

1 subclass:

- [`FileHelper`](/docs/api/yii/helpers/filehelper/index.md)

BaseFileHelper provides concrete implementation for [`FileHelper`](/docs/api/yii/helpers/filehelper/index.md).

Do not use BaseFileHelper. Use [`FileHelper`](/docs/api/yii/helpers/filehelper/index.md) instead.

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| <span id="property-mimeAliasesFile"></span>`$mimeAliasesFile` static | `string` | The path (or alias) of a PHP file containing MIME aliases. Default: `'@yii/helpers/mimeAliases.php'`. Available since 2.0.14. | `BaseFileHelper` |
| <span id="property-mimeExtensionsFile"></span>`$mimeExtensionsFile` static | `string` | The path (or alias) of a PHP file containing extensions per MIME type. Default: `'@yii/helpers/mimeExtensions.php'`. Available since 2.0.48. | `BaseFileHelper` |
| <span id="property-mimeMagicFile"></span>`$mimeMagicFile` static | `string` | The path (or alias) of a PHP file containing MIME type information. Default: `'@yii/helpers/mimeTypes.php'`. | `BaseFileHelper` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`changeOwnership()`](#method-changeOwnership) static | Changes the Unix user and/or group ownership of a file or directory, and optionally the mode. | `BaseFileHelper` |
| [`copyDirectory()`](#method-copyDirectory) static | Copies a whole directory as another one. | `BaseFileHelper` |
| [`createDirectory()`](#method-createDirectory) static | Creates a new directory. | `BaseFileHelper` |
| [`filterPath()`](#method-filterPath) static | Checks if the given file path satisfies the filtering options. | `BaseFileHelper` |
| [`findDirectories()`](#method-findDirectories) static | Returns the directories found under the specified directory and subdirectories. | `BaseFileHelper` |
| [`findFiles()`](#method-findFiles) static | Returns the files found under the specified directory and subdirectories. | `BaseFileHelper` |
| [`getExtensionByMimeType()`](#method-getExtensionByMimeType) static | Determines the most common extension by given MIME type. | `BaseFileHelper` |
| [`getExtensionsByMimeType()`](#method-getExtensionsByMimeType) static | Determines the extensions by given MIME type. | `BaseFileHelper` |
| [`getMimeType()`](#method-getMimeType) static | Determines the MIME type of the specified file. | `BaseFileHelper` |
| [`getMimeTypeByExtension()`](#method-getMimeTypeByExtension) static | Determines the MIME type based on the extension name of the specified file. | `BaseFileHelper` |
| [`localize()`](#method-localize) static | Returns the localized version of a specified file. | `BaseFileHelper` |
| [`normalizePath()`](#method-normalizePath) static | Normalizes a file/directory path. | `BaseFileHelper` |
| [`removeDirectory()`](#method-removeDirectory) static | Removes a directory (and all its content) recursively. | `BaseFileHelper` |
| [`unlink()`](#method-unlink) static | Removes a file or symlink in a cross-platform way | `BaseFileHelper` |
| [`loadMimeAliases()`](#method-loadMimeAliases) protected static | Loads MIME aliases from the specified file. | `BaseFileHelper` |
| [`loadMimeExtensions()`](#method-loadMimeExtensions) protected static | Loads MIME extensions from the specified file. | `BaseFileHelper` |
| [`loadMimeTypes()`](#method-loadMimeTypes) protected static | Loads MIME types from the specified file. | `BaseFileHelper` |
| [`normalizeOptions()`](#method-normalizeOptions) protected static |  | `BaseFileHelper` |

## Constants

| Constant | Value | Description | Defined by |
| --- | --- | --- | --- |
| <span id="const-PATTERN_NODIR"></span>`PATTERN_NODIR` | `1` |  | `BaseFileHelper` |
| <span id="const-PATTERN_ENDSWITH"></span>`PATTERN_ENDSWITH` | `4` |  | `BaseFileHelper` |
| <span id="const-PATTERN_MUSTBEDIR"></span>`PATTERN_MUSTBEDIR` | `8` |  | `BaseFileHelper` |
| <span id="const-PATTERN_NEGATIVE"></span>`PATTERN_NEGATIVE` | `16` |  | `BaseFileHelper` |
| <span id="const-PATTERN_CASE_INSENSITIVE"></span>`PATTERN_CASE_INSENSITIVE` | `32` |  | `BaseFileHelper` |

## Method details

### changeOwnership() <span id="method-changeOwnership"></span>

```php
public static function changeOwnership(string $path, string|array|int|null $ownership, int|null $mode = null): mixed
```

Changes the Unix user and/or group ownership of a file or directory, and optionally the mode.

Note: This function will not work on remote files as the file to be examined must be accessible
via the server's filesystem.
Note: On Windows, this function fails silently when applied on a regular file.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$path` | `string` | The path to the file or directory. |
| `$ownership` | `string\|array\|int\|null` | The user and/or group ownership for the file or directory. When $ownership is a string, the format is 'user:group' where both are optional. E.g. 'user' or 'user:' will only change the user, ':group' will only change the group, 'user:group' will change both. When $owners is an index array the format is [0 => user, 1 => group], e.g. `[$myUser, $myGroup]`. It is also possible to pass an associative array, e.g. ['user' => $myUser, 'group' => $myGroup]. In case $owners is an integer it will be used as user id. If `null`, an empty array or an empty string is passed, the ownership will not be changed. |
| `$mode` | `int\|null` | The permission to be set for the file or directory. If `null` is passed, the mode will not be changed. |

**Returns**

`mixed`

**Since**

2.0.43

### copyDirectory() <span id="method-copyDirectory"></span>

```php
public static function copyDirectory(string $src, string $dst, array $options = []): mixed
```

Copies a whole directory as another one.

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

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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. |

**Returns**

`mixed`

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if unable to open directory

### createDirectory() <span id="method-createDirectory"></span>

```php
public static function createDirectory(string $path, int $mode = 0775, bool $recursive = true): bool
```

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.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$path` | `string` | Path of the directory to be created. |
| `$mode` | `int` | The permission to be set for the created directory. |
| `$recursive` | `bool` | Whether to create parent directories if they do not exist. |

**Returns**

`bool`: Whether the directory is created successfully

**Throws**

- [`yii\base\Exception`](/docs/api/yii/base/exception/index.md): if the directory could not be created (i.e. php error due to parallel changes)

### filterPath() <span id="method-filterPath"></span>

```php
public static function filterPath(string $path, array $options): bool
```

Checks if the given file path satisfies the filtering options.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$path` | `string` | The path of the file or directory to be checked |
| `$options` | `array` | The filtering options. See [`findFiles()`](/docs/api/yii/helpers/basefilehelper/index.md#method-findFiles) for explanations of the supported options. |

**Returns**

`bool`: Whether the file or directory satisfies the filtering options.

### findDirectories() <span id="method-findDirectories"></span>

```php
public static function findDirectories(string $dir, array $options = []): array
```

Returns the directories found under the specified directory and subdirectories.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$dir` | `string` | The directory under which the files will be looked for. |
| `$options` | `array` | Options for directory searching. Valid options are: - `filter`: callback, a PHP callback that is called for each directory or file. The signature of the callback should be: `function (string $path): bool`, where `$path` refers the full path to be filtered. The callback can return one of the following values: * `true`: the directory will be returned * `false`: the directory will NOT be returned - `recursive`: boolean, whether the files under the subdirectories should also be looked for. Defaults to `true`. See [`findFiles()`](/docs/api/yii/helpers/basefilehelper/index.md#method-findFiles) for more options. |

**Returns**

`array`: Directories found under the directory, in no particular order. Ordering depends on the files system used.

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the dir is invalid.

**Since**

2.0.14

### findFiles() <span id="method-findFiles"></span>

```php
public static function findFiles(string $dir, array $options = []): array
```

Returns the files found under the specified directory and subdirectories.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$dir` | `string` | The directory under which the files will be looked for. |
| `$options` | `array` | Options for file searching. Valid options are: - `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 returned (the `only` and `except` options will be ignored) * `false`: the directory or file will NOT be returned (the `only` and `except` options will be ignored) * `null`: the `only` and `except` options will determine whether the directory or file should be returned - `except`: array, list of patterns excluding from the results matching file or directory paths. Patterns ending with slash ('/') 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`. If the pattern does not contain a slash (`/`), it is treated as a shell glob pattern and checked for a match against the pathname relative to `$dir`. Otherwise, the pattern is treated as a shell glob suitable for consumption by `fnmatch(3)` with the `FNM_PATHNAME` flag: wildcards in the pattern will not match a `/` in the pathname. For example, `views/*.php` matches `views/index.php` but not `views/controller/index.php`. A leading slash matches the beginning of the pathname. For example, `/*.php` matches `index.php` but not `views/start/index.php`. An optional prefix `!` which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources. Put a backslash (`\`) in front of the first `!` for patterns that begin with a literal `!`, for example, `\!important!.txt`. Note, the '/' characters in a pattern matches both '/' and '\' in the paths. You can find more details about the gitignore pattern format [here](https://git-scm.com/docs/gitignore/en#_pattern_format). - `only`: array, list of patterns that the file paths should match if they are to be returned. Directory paths are not checked against them. Same pattern matching rules as in the `except` option are used. If a file path matches a pattern in both `only` and `except`, it will NOT be returned. - `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 looked for. Defaults to `true`. |

**Returns**

`array`: Files found under the directory, in no particular order. Ordering depends on the files system used.

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the dir is invalid.

### getExtensionByMimeType() <span id="method-getExtensionByMimeType"></span>

```php
public static function getExtensionByMimeType(string $mimeType, bool $preferShort = false, string|null $magicFile = null): string|null
```

Determines the most common extension by given MIME type.

This method will use a local map between MIME types and extension names.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$mimeType` | `string` | File MIME type. |
| `$preferShort` | `bool` | Return an extension with a maximum of 3 characters. |
| `$magicFile` | `string\|null` | The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by [`$mimeMagicFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeMagicFile) will be used. |

**Returns**

`string|null`: The extensions corresponding to the specified MIME type

**Since**

2.0.48

### getExtensionsByMimeType() <span id="method-getExtensionsByMimeType"></span>

```php
public static function getExtensionsByMimeType(string $mimeType, string|null $magicFile = null): array
```

Determines the extensions by given MIME type.

This method will use a local map between extension names and MIME types.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$mimeType` | `string` | File MIME type. |
| `$magicFile` | `string\|null` | The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by [`$mimeMagicFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeMagicFile) will be used. |

**Returns**

`array`: The extensions corresponding to the specified MIME type

### getMimeType() <span id="method-getMimeType"></span>

```php
public static function getMimeType(string $file, string|null $magicFile = null, bool $checkExtension = true): string|null
```

Determines the MIME type of the specified file.

This method will first try to determine the MIME type based on
[finfo_open](https://www.php.net/manual/en/function.finfo-open.php). If the `fileinfo` extension is not installed,
it will fall back to [`getMimeTypeByExtension()`](/docs/api/yii/helpers/basefilehelper/index.md#method-getMimeTypeByExtension) when `$checkExtension` is true.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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()](https://www.php.net/manual/en/function.finfo-open.php) when the `fileinfo` extension is installed. If the MIME type is being determined based via [`getMimeTypeByExtension()`](/docs/api/yii/helpers/basefilehelper/index.md#method-getMimeTypeByExtension) and this is null, it will use the file specified by [`$mimeMagicFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeMagicFile). |
| `$checkExtension` | `bool` | Whether to use the file extension to determine the MIME type in case `finfo_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`](/docs/api/yii/base/invalidconfigexception/index.md): when the `fileinfo` PHP extension is not installed and `$checkExtension` is `false`.

### getMimeTypeByExtension() <span id="method-getMimeTypeByExtension"></span>

```php
public static function getMimeTypeByExtension(string $file, string|null $magicFile = null): string|null
```

Determines the MIME type based on the extension name of the specified file.

This method will use a local map between extension names and MIME types.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$file` | `string` | The file name. |
| `$magicFile` | `string\|null` | The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by [`$mimeMagicFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeMagicFile) will be used. |

**Returns**

`string|null`: The MIME type. Null is returned if the MIME type cannot be determined.

### localize() <span id="method-localize"></span>

```php
public static function localize(string $file, string|null $language = null, string|null $sourceLanguage = null): string
```

Returns the localized version of a specified file.

The searching is based on the specified language code. In particular,
a file with the same name will be looked for under the subdirectory
whose name is the same as the language code. For example, given the file "path/to/view.php"
and language code "zh-CN", the localized file will be looked for as
"path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
"zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.

If the target and the source language codes are the same, the original file will be returned.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$file` | `string` | The original file |
| `$language` | `string\|null` | The target language that the file should be localized to. If not set, the value of [`Application::$language`](/docs/api/yii/base/application/index.md#property-language) will be used. |
| `$sourceLanguage` | `string\|null` | The language that the original file is in. If not set, the value of [`Application::$sourceLanguage`](/docs/api/yii/base/application/index.md#property-sourceLanguage) will be used. |

**Returns**

`string`: The matching localized file, or the original file if the localized version is not found. If the target and the source language codes are the same, the original file will be returned.

### normalizePath() <span id="method-normalizePath"></span>

```php
public static function normalizePath(string $path, string $ds = \yii\helpers\DIRECTORY_SEPARATOR): string
```

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.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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

### removeDirectory() <span id="method-removeDirectory"></span>

```php
public static function removeDirectory(string $dir, array $options = []): mixed
```

Removes a directory (and all its content) recursively.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$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. |

**Returns**

`mixed`

**Throws**

- [`yii\base\ErrorException`](/docs/api/yii/base/errorexception/index.md): in case of failure

### unlink() <span id="method-unlink"></span>

```php
public static function unlink(string $path): bool
```

Removes a file or symlink in a cross-platform way

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$path` | `string` |  |

**Returns**

`bool`

**Since**

2.0.14

### loadMimeAliases() <span id="method-loadMimeAliases"></span>

```php
protected static function loadMimeAliases(string|null $aliasesFile): array
```

Loads MIME aliases from the specified file.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$aliasesFile` | `string\|null` | The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by [`$mimeAliasesFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeAliasesFile) will be used. |

**Returns**

`array`: The mapping from file extensions to MIME types

**Since**

2.0.14

### loadMimeExtensions() <span id="method-loadMimeExtensions"></span>

```php
protected static function loadMimeExtensions(string|null $extensionsFile): array
```

Loads MIME extensions from the specified file.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$extensionsFile` | `string\|null` | The path (or alias) of the file that contains MIME type aliases. If this is not set, the file specified by [`$mimeAliasesFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeAliasesFile) will be used. |

**Returns**

`array`: The mapping from file extensions to MIME types

**Since**

2.0.48

### loadMimeTypes() <span id="method-loadMimeTypes"></span>

```php
protected static function loadMimeTypes(string|null $magicFile): array
```

Loads MIME types from the specified file.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$magicFile` | `string\|null` | The path (or alias) of the file that contains all available MIME type information. If this is not set, the file specified by [`$mimeMagicFile`](/docs/api/yii/helpers/basefilehelper/index.md#property-mimeMagicFile) will be used. |

**Returns**

`array`: The mapping from file extensions to MIME types

### normalizeOptions() <span id="method-normalizeOptions"></span>

```php
protected static function normalizeOptions(array $options): array
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$options` | `array` | Raw options |

**Returns**

`array`: Normalized options

**Since**

2.0.12