Skip to content

The Filesystem Component

Warning: You are browsing the documentation for Symfony 4.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

The Filesystem component provides basic utilities for the filesystem.

Installation

1
$ composer require symfony/filesystem

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Usage

The Filesystem class is the unique endpoint for filesystem operations:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;

$filesystem = new Filesystem();

try {
    $filesystem->mkdir(sys_get_temp_dir().'/'.random_int(0, 1000));
} catch (IOExceptionInterface $exception) {
    echo "An error occurred while creating your directory at ".$exception->getPath();
}

mkdir

mkdir() creates a directory recursively. On POSIX filesystems, directories are created with a default mode value 0777. You can use the second argument to set your own mode:

1
$filesystem->mkdir('/tmp/photos', 0700);

Note

You can pass an array or any Traversable object as the first argument.

Note

This function ignores already existing directories.

Note

The directory permissions are affected by the current umask. Set the umask for your webserver, use PHP's umask function or use the chmod function after the directory has been created.

exists

exists() checks for the presence of one or more files or directories and returns false if any of them is missing:

1
2
3
4
5
6
// if this absolute directory exists, returns true
$filesystem->exists('/tmp/photos');

// if rabbit.jpg exists and bottle.png does not exist, returns false
// non-absolute paths are relative to the directory where the running PHP script is stored
$filesystem->exists(['rabbit.jpg', 'bottle.png']);

Note

You can pass an array or any Traversable object as the first argument.

copy

copy() makes a copy of a single file (use mirror() to copy directories). If the target already exists, the file is copied only if the source modification date is later than the target. This behavior can be overridden by the third boolean argument:

1
2
3
4
5
// works only if image-ICC has been modified after image.jpg
$filesystem->copy('image-ICC.jpg', 'image.jpg');

// image.jpg will be overridden
$filesystem->copy('image-ICC.jpg', 'image.jpg', true);

touch

touch() sets access and modification time for a file. The current time is used by default. You can set your own with the second argument. The third argument is the access time:

1
2
3
4
5
6
// sets modification time to the current timestamp
$filesystem->touch('file.txt');
// sets modification time 10 seconds in the future
$filesystem->touch('file.txt', time() + 10);
// sets access time 10 seconds in the past
$filesystem->touch('file.txt', time(), time() - 10);

Note

You can pass an array or any Traversable object as the first argument.

chown

chown() changes the owner of a file. The third argument is a boolean recursive option:

1
2
3
4
// sets the owner of the lolcat video to www-data
$filesystem->chown('lolcat.mp4', 'www-data');
// changes the owner of the video directory recursively
$filesystem->chown('/video', 'www-data', true);

Note

You can pass an array or any Traversable object as the first argument.

chgrp

chgrp() changes the group of a file. The third argument is a boolean recursive option:

1
2
3
4
// sets the group of the lolcat video to nginx
$filesystem->chgrp('lolcat.mp4', 'nginx');
// changes the group of the video directory recursively
$filesystem->chgrp('/video', 'nginx', true);

Note

You can pass an array or any Traversable object as the first argument.

chmod

chmod() changes the mode or permissions of a file. The fourth argument is a boolean recursive option:

1
2
3
4
// sets the mode of the video to 0600
$filesystem->chmod('video.ogg', 0600);
// changes the mode of the src directory recursively
$filesystem->chmod('src', 0700, 0000, true);

Note

You can pass an array or any Traversable object as the first argument.

remove

remove() deletes files, directories and symlinks:

1
$filesystem->remove(['symlink', '/path/to/directory', 'activity.log']);

Note

You can pass an array or any Traversable object as the first argument.

rename

rename() changes the name of a single file or directory:

1
2
3
4
5
6
// renames a file
$filesystem->rename('/tmp/processed_video.ogg', '/path/to/store/video_647.ogg');
// renames a directory
$filesystem->rename('/tmp/files', '/path/to/store/files');
// if the target already exists, a third boolean argument is available to overwrite.
$filesystem->rename('/tmp/processed_video2.ogg', '/path/to/store/video_647.ogg', true);

symlink() creates a symbolic link from the target to the destination. If the filesystem does not support symbolic links, a third boolean argument is available:

1
2
3
4
5
// creates a symbolic link
$filesystem->symlink('/path/to/source', '/path/to/destination');
// duplicates the source directory if the filesystem
// does not support symbolic links
$filesystem->symlink('/path/to/source', '/path/to/destination', true);

readlink() read links targets.

The readlink() method provided by the Filesystem component behaves in the same way on all operating systems (unlike PHP's readlink function):

1
2
3
4
5
// returns the next direct target of the link without considering the existence of the target
$filesystem->readlink('/path/to/link');

// returns its absolute fully resolved final version of the target (if there are nested links, they are resolved)
$filesystem->readlink('/path/to/link', true);

Its behavior is the following:

  • When $canonicalize is false (the default value):
    • if $path does not exist or is not a link, it returns null.
    • if $path is a link, it returns the next direct target of the link without considering the existence of the target.
  • When $canonicalize is true:
    • if $path does not exist, it returns null.
    • if $path exists, it returns its absolute fully resolved final version.

makePathRelative

makePathRelative() takes two absolute paths and returns the relative path from the second path to the first one:

1
2
3
4
5
6
7
// returns '../'
$filesystem->makePathRelative(
    '/var/lib/symfony/src/Symfony/',
    '/var/lib/symfony/src/Symfony/Component'
);
// returns 'videos/'
$filesystem->makePathRelative('/tmp/videos', '/tmp');

mirror

mirror() copies all the contents of the source directory into the target one (use the copy() method to copy single files):

1
$filesystem->mirror('/path/to/source', '/path/to/target');

isAbsolutePath

isAbsolutePath() returns true if the given path is absolute, false otherwise:

1
2
3
4
5
6
7
8
// returns true
$filesystem->isAbsolutePath('/tmp');
// returns true
$filesystem->isAbsolutePath('c:\\Windows');
// returns false
$filesystem->isAbsolutePath('tmp');
// returns false
$filesystem->isAbsolutePath('../dir');

tempnam

tempnam() creates a temporary file with a unique filename, and returns its path, or throw an exception on failure:

1
2
// returns a path like : /tmp/prefix_wyjgtF
$filesystem->tempnam('/tmp', 'prefix_');

dumpFile

dumpFile() saves the given contents into a file. It does this in an atomic manner: it writes a temporary file first and then moves it to the new file location when it's finished. This means that the user will always see either the complete old file or complete new file (but never a partially-written file):

1
$filesystem->dumpFile('file.txt', 'Hello World');

The file.txt file contains Hello World now.

appendToFile

appendToFile() adds new contents at the end of some file:

1
$filesystem->appendToFile('logs.txt', 'Email sent to user@example.com');

If either the file or its containing directory doesn't exist, this method creates them before appending the contents.

Error Handling

Whenever something wrong happens, an exception implementing ExceptionInterface or IOExceptionInterface is thrown.

Note

An IOException is thrown if directory creation fails.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version