class FileSystem implements FileSystemInterface (View source)

Provides helpers to operate on files and stream wrappers.

Constants

CHMOD_DIRECTORY

Default mode for new directories. See self::chmod().

CHMOD_FILE

Default mode for new files. See self::chmod().

Properties

protected Settings $settings

The site settings.

protected LoggerInterface $logger

The file logger channel.

protected StreamWrapperManagerInterface $streamWrapperManager

The stream wrapper manager.

Methods

__construct(StreamWrapperManagerInterface $stream_wrapper_manager, Settings $settings, LoggerInterface $logger)

Constructs a new FileSystem.

bool
moveUploadedFile(string $filename, string $uri)

Moves an uploaded file to a new location.

bool
chmod(string $uri, int $mode = NULL)

Sets the permissions on a file or directory.

bool
unlink(string $uri, resource $context = NULL)

Deletes a file.

string|false
realpath(string $uri)

Resolves the absolute filepath of a local URI or filepath.

string
dirname(string $uri)

Gets the name of the directory from a given path.

basename($uri, $suffix = NULL)

Gets the filename from a given path.

bool
mkdir(string $uri, int $mode = NULL, bool $recursive = FALSE, resource $context = NULL)

Creates a directory, optionally creating missing components in the path to the directory.

mkdirCall($uri, $mode, $recursive, $context)

Helper function. Ensures we don't pass a NULL as a context resource to mkdir().

bool
rmdir(string $uri, resource $context = NULL)

Removes a directory.

string|bool
tempnam(string $directory, string $prefix)

Creates a file with a unique filename in the specified directory.

string
copy(string $source, string $destination, int $replace = self::EXISTS_RENAME)

Copies a file to a new location without invoking the file API.

delete(string $path)

Deletes a file without database changes or hook invocations.

deleteRecursive(string $path, callable $callback = NULL)

Deletes all files and directories in the specified filepath recursively.

string
move(string $source, string $destination, int $replace = self::EXISTS_RENAME)

Moves a file to a new location without database changes or hook invocation.

prepareDestination(string $source, string|null $destination, int $replace)

Prepares the destination for a file copy or move operation.

string
saveData(string $data, string $destination, int $replace = self::EXISTS_RENAME)

Saves a file to the specified destination without invoking file API.

bool
prepareDirectory(string $directory, int $options = self::MODIFY_PERMISSIONS)

Checks that the directory exists and is writable.

string|bool
getDestinationFilename(string $destination, int $replace)

Determines the destination path for a file.

string
createFilename(string $basename, string $directory)

Creates a full file path from a directory and filename.

string
getTempDirectory()

Gets the path of the configured temporary directory.

array
scanDirectory(string $dir, string $mask, array $options = [])

Finds all files that match a given mask in a given directory.

array
doScanDirectory(string $dir, string $mask, array $options = [], int $depth = 0)

Internal function to handle directory scanning with recursion.

Details

__construct(StreamWrapperManagerInterface $stream_wrapper_manager, Settings $settings, LoggerInterface $logger)

Constructs a new FileSystem.

Parameters

StreamWrapperManagerInterface $stream_wrapper_manager

The stream wrapper manager.

Settings $settings

The site settings.

LoggerInterface $logger

The file logger channel.

bool moveUploadedFile(string $filename, string $uri)

Moves an uploaded file to a new location.

PHP's move_uploaded_file() does not properly support streams if open_basedir is enabled, so this function fills that gap.

Compatibility: normal paths and stream wrappers.

Parameters

string $filename

The filename of the uploaded file.

string $uri

A string containing the destination URI of the file.

Return Value

bool

TRUE on success, or FALSE on failure.

bool chmod(string $uri, int $mode = NULL)

Sets the permissions on a file or directory.

This function will use the file_chmod_directory and file_chmod_file settings for the default modes for directories and uploaded/generated files. By default these will give everyone read access so that users accessing the files with a user account without the webserver group (e.g. via FTP) can read these files, and give group write permissions so webserver group members (e.g. a vhost account) can alter files uploaded and owned by the webserver.

PHP's chmod does not support stream wrappers so we use our wrapper implementation which interfaces with chmod() by default. Contrib wrappers may override this behavior in their implementations as needed.

Parameters

string $uri

A string containing a URI file, or directory path.

int $mode

Integer value for the permissions. Consult PHP chmod() documentation for more information.

Return Value

bool

TRUE for success, FALSE in the event of an error.

Deletes a file.

PHP's unlink() is broken on Windows, as it can fail to remove a file when it has a read-only flag set.

Parameters

string $uri

A URI or pathname.

resource $context

Refer to http://php.net/manual/ref.stream.php

Return Value

bool

Boolean TRUE on success, or FALSE on failure.

string|false realpath(string $uri)

Resolves the absolute filepath of a local URI or filepath.

The use of this method is discouraged, because it does not work for remote URIs. Except in rare cases, URIs should not be manually resolved.

Only use this function if you know that the stream wrapper in the URI uses the local file system, and you need to pass an absolute path to a function that is incompatible with stream URIs.

Parameters

string $uri

A stream wrapper URI or a filepath, possibly including one or more symbolic links.

Return Value

string|false

The absolute local filepath (with no symbolic links) or FALSE on failure.

string dirname(string $uri)

Gets the name of the directory from a given path.

PHP's dirname() does not properly pass streams, so this function fills that gap. It is backwards compatible with normal paths and will use PHP's dirname() as a fallback.

Compatibility: normal paths and stream wrappers.

Parameters

string $uri

A URI or path.

Return Value

string

A string containing the directory name.

basename($uri, $suffix = NULL)

Gets the filename from a given path.

PHP's basename() does not properly support streams or filenames beginning with a non-US-ASCII character.

Parameters

$uri
$suffix

bool mkdir(string $uri, int $mode = NULL, bool $recursive = FALSE, resource $context = NULL)

Creates a directory, optionally creating missing components in the path to the directory.

When PHP's mkdir() creates a directory, the requested mode is affected by the process's umask. This function overrides the umask and sets the mode explicitly for all directory components created.

Parameters

string $uri

A URI or pathname.

int $mode

Mode given to created directories. Defaults to the directory mode configured in the Drupal installation. It must have a leading zero.

bool $recursive

Create directories recursively, defaults to FALSE. Cannot work with a mode which denies writing or execution to the owner of the process.

resource $context

Refer to http://php.net/manual/ref.stream.php

Return Value

bool

Boolean TRUE on success, or FALSE on failure.

protected mkdirCall($uri, $mode, $recursive, $context)

Helper function. Ensures we don't pass a NULL as a context resource to mkdir().

Parameters

$uri
$mode
$recursive
$context

See also

\Drupal\Core\File\self::mkdir()

bool rmdir(string $uri, resource $context = NULL)

Removes a directory.

PHP's rmdir() is broken on Windows, as it can fail to remove a directory when it has a read-only flag set.

Parameters

string $uri

A URI or pathname.

resource $context

Refer to http://php.net/manual/ref.stream.php

Return Value

bool

Boolean TRUE on success, or FALSE on failure.

string|bool tempnam(string $directory, string $prefix)

Creates a file with a unique filename in the specified directory.

PHP's tempnam() does not return a URI like we want. This function will return a URI if given a URI, or it will return a filepath if given a filepath.

Compatibility: normal paths and stream wrappers.

Parameters

string $directory

The directory where the temporary filename will be created.

string $prefix

The prefix of the generated temporary filename. Note: Windows uses only the first three characters of prefix.

Return Value

string|bool

The new temporary filename, or FALSE on failure.

string copy(string $source, string $destination, int $replace = self::EXISTS_RENAME)

Copies a file to a new location without invoking the file API.

This is a powerful function that in many ways performs like an advanced version of copy().

  • Checks if $source and $destination are valid and readable/writable.
  • If file already exists in $destination either the call will error out, replace the file or rename the file based on the $replace parameter.
  • If the $source and $destination are equal, the behavior depends on the $replace parameter. FileSystemInterface::EXISTS_REPLACE will replace the existing file. FileSystemInterface::EXISTS_ERROR will error out. FileSystemInterface::EXISTS_RENAME will rename the file until the $destination is unique.
  • Provides a fallback using realpaths if the move fails using stream wrappers. This can occur because PHP's copy() function does not properly support streams if open_basedir is enabled. See https://bugs.php.net/bug.php?id=60456

Parameters

string $source

A string specifying the filepath or URI of the source file.

string $destination

A URI containing the destination that $source should be copied to. The URI may be a bare filepath (without a scheme).

int $replace

Replace behavior when the destination file already exists:

  • FileSystemInterface::EXISTS_REPLACE - Replace the existing file.
  • FileSystemInterface::EXISTSRENAME - Append {incrementing number} until the filename is unique.
  • FileSystemInterface::EXISTS_ERROR - Throw an exception.

Return Value

string

The path to the new file.

Exceptions

FileException

delete(string $path)

Deletes a file without database changes or hook invocations.

This function should be used when the file to be deleted does not have an entry recorded in the files table.

Parameters

string $path

A string containing a file path or (streamwrapper) URI.

Exceptions

FileException

deleteRecursive(string $path, callable $callback = NULL)

Deletes all files and directories in the specified filepath recursively.

If the specified path is a directory then the function is called recursively to process the contents. Once the contents have been removed the directory is also removed.

If the specified path is a file then it will be processed with delete() method.

Note that this only deletes visible files with write permission.

Parameters

string $path

A string containing either an URI or a file or directory path.

callable $callback

Callback function to run on each file prior to deleting it and on each directory prior to traversing it. For example, can be used to modify permissions.

Exceptions

FileException

string move(string $source, string $destination, int $replace = self::EXISTS_RENAME)

Moves a file to a new location without database changes or hook invocation.

This is a powerful function that in many ways performs like an advanced version of rename().

  • Checks if $source and $destination are valid and readable/writable.
  • Checks that $source is not equal to $destination; if they are an error is reported.
  • If file already exists in $destination either the call will error out, replace the file or rename the file based on the $replace parameter.
  • Works around a PHP bug where rename() does not properly support streams if safe_mode or open_basedir are enabled.

Parameters

string $source

A string specifying the filepath or URI of the source file.

string $destination

A URI containing the destination that $source should be moved to. The URI may be a bare filepath (without a scheme) and in that case the default scheme (public://) will be used.

int $replace

Replace behavior when the destination file already exists:

  • FileSystemInterface::EXISTS_REPLACE - Replace the existing file.
  • FileSystemInterface::EXISTSRENAME - Append {incrementing number} until the filename is unique.
  • FileSystemInterface::EXISTS_ERROR - Do nothing and return FALSE.

Return Value

string

The path to the new file.

Exceptions

FileException

protected prepareDestination(string $source, string|null $destination, int $replace)

Prepares the destination for a file copy or move operation.

  • Checks if $source and $destination are valid and readable/writable.
  • Checks that $source is not equal to $destination; if they are an error is reported.
  • If file already exists in $destination either the call will error out, replace the file or rename the file based on the $replace parameter.

Parameters

string $source

A string specifying the filepath or URI of the source file.

string|null $destination

A URI containing the destination that $source should be moved/copied to. The URI may be a bare filepath (without a scheme) and in that case the default scheme (file://) will be used.

int $replace

Replace behavior when the destination file already exists:

  • FileSystemInterface::EXISTS_REPLACE - Replace the existing file.
  • FileSystemInterface::EXISTSRENAME - Append {incrementing number} until the filename is unique.
  • FileSystemInterface::EXISTS_ERROR - Do nothing and return FALSE.

See also

FileSystemInterface::copy
FileSystemInterface::move

string saveData(string $data, string $destination, int $replace = self::EXISTS_RENAME)

Saves a file to the specified destination without invoking file API.

This function is identical to file_save_data() except the file will not be saved to the {filemanaged} table and none of the file* hooks will be called.

Parameters

string $data

A string containing the contents of the file.

string $destination

A string containing the destination location. This must be a stream wrapper URI.

int $replace

Replace behavior when the destination file already exists:

  • FileSystemInterface::EXISTS_REPLACE - Replace the existing file.
  • FileSystemInterface::EXISTSRENAME - Append {incrementing number} until the filename is unique.
  • FileSystemInterface::EXISTS_ERROR - Do nothing and return FALSE.

Return Value

string

A string with the path of the resulting file, or FALSE on error.

Exceptions

FileException

bool prepareDirectory(string $directory, int $options = self::MODIFY_PERMISSIONS)

Checks that the directory exists and is writable.

Directories need to have execute permissions to be considered a directory by FTP servers, etc.

Parameters

string $directory

A string reference containing the name of a directory path or URI. A trailing slash will be trimmed from a path.

int $options

A bitmask to indicate if the directory should be created if it does not exist (FileSystemInterface::CREATE_DIRECTORY) or made writable if it is read-only (FileSystemInterface::MODIFY_PERMISSIONS).

Return Value

bool

TRUE if the directory exists (or was created) and is writable. FALSE otherwise.

string|bool getDestinationFilename(string $destination, int $replace)

Determines the destination path for a file.

Parameters

string $destination

The desired final URI or filepath.

int $replace

Replace behavior when the destination file already exists.

  • FileSystemInterface::EXISTS_REPLACE - Replace the existing file.
  • FileSystemInterface::EXISTSRENAME - Append {incrementing number} until the filename is unique.
  • FileSystemInterface::EXISTS_ERROR - Do nothing and return FALSE.

Return Value

string|bool

The destination filepath, or FALSE if the file already exists and FileSystemInterface::EXISTS_ERROR is specified.

Exceptions

FileException

string createFilename(string $basename, string $directory)

Creates a full file path from a directory and filename.

If a file with the specified name already exists, an alternative will be used.

Parameters

string $basename

The filename.

string $directory

The directory or parent URI.

Return Value

string

File path consisting of $directory and a unique filename based off of $basename.

Exceptions

FileException

string getTempDirectory()

Gets the path of the configured temporary directory.

If the path is not set, it will fall back to the OS-specific default if set, otherwise a directory under the public files directory. It will then set this as the configured directory.

Return Value

string

A string containing the path to the temporary directory.

array scanDirectory(string $dir, string $mask, array $options = [])

Finds all files that match a given mask in a given directory.

Directories and files beginning with a dot are excluded; this prevents hidden files and directories (such as SVN working directories) from being scanned. Use the umask option to skip configuration directories to eliminate the possibility of accidentally exposing configuration information. Also, you can use the base directory, recurse, and min_depth options to improve performance by limiting how much of the filesystem has to be traversed.

Parameters

string $dir

The base directory or URI to scan, without trailing slash.

string $mask

The preg_match() regular expression for files to be included.

array $options

An associative array of additional options, with the following elements:

  • 'nomask': The preg_match() regular expression for files to be excluded. Defaults to the 'file_scan_ignore_directories' setting.
  • 'callback': The callback function to call for each match. There is no default callback.
  • 'recurse': When TRUE, the directory scan will recurse the entire tree starting at the provided directory. Defaults to TRUE.
  • 'key': The key to be used for the returned associative array of files. Possible values are 'uri', for the file's URI; 'filename', for the basename of the file; and 'name' for the name of the file without the extension. Defaults to 'uri'.
  • 'min_depth': Minimum depth of directories to return files from. Defaults to 0.

Return Value

array

An associative array (keyed on the chosen key) of objects with 'uri', 'filename', and 'name' properties corresponding to the matched files.

Exceptions

NotRegularDirectoryException

protected array doScanDirectory(string $dir, string $mask, array $options = [], int $depth = 0)

Internal function to handle directory scanning with recursion.

Parameters

string $dir

The base directory or URI to scan, without trailing slash.

string $mask

The preg_match() regular expression for files to be included.

array $options

The options as per ::scanDirectory().

int $depth

The current depth of recursion.

Return Value

array

An associative array as per ::scanDirectory().

Exceptions

NotRegularDirectoryException

See also

FileSystemInterface::scanDirectory