The Filesystem Component

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 mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Usage

The Filesystem class is the uniqueendpoint for filesystem operations:

  1. use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
  2. use Symfony\Component\Filesystem\Filesystem;
  3.  
  4. $filesystem = new Filesystem();
  5.  
  6. try {
  7. $filesystem->mkdir(sys_get_temp_dir().'/'.random_int(0, 1000));
  8. } catch (IOExceptionInterface $exception) {
  9. echo "An error occurred while creating your directory at ".$exception->getPath();
  10. }

Note

Methods mkdir(),exists(),touch(),remove(),chmod(),chown() andchgrp() can receive astring, an array or any object implementing Traversable asthe target argument.

mkdir

mkdir() creates a directory recursively.On POSIX filesystems, directories are created with a default mode value0777. 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 firstargument.

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 umaskfunction or use the chmod function after thedirectory has been created.

exists

exists() checks for thepresence of one or more files or directories and returns false if any ofthem is missing:

  1. // if this absolute directory exists, returns true
  2. $filesystem->exists('/tmp/photos');
  3.  
  4. // if rabbit.jpg exists and bottle.png does not exist, returns false
  5. // non-absolute paths are relative to the directory where the running PHP script is stored
  6. $filesystem->exists(['rabbit.jpg', 'bottle.png']);

Note

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

copy

copy() makes a copy of asingle file (use mirror() tocopy directories). If the target already exists, the file is copied only if thesource modification date is later than the target. This behavior can be overriddenby the third boolean argument:

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

touch

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

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

Note

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

chown

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

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

Note

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

chgrp

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

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

Note

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

chmod

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

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

Note

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

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 firstargument.

rename

rename() changes the nameof a single file or directory:

  1. // renames a file
  2. $filesystem->rename('/tmp/processed_video.ogg', '/path/to/store/video_647.ogg');
  3. // renames a directory
  4. $filesystem->rename('/tmp/files', '/path/to/store/files');

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

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

readlink() read links targets.

PHP's readlink() function returns the target of a symbolic link. However, its behavioris completely different under Windows and Unix. On Windows systems, readlink()resolves recursively the children links of a link until a final target is found. OnUnix-based systems readlink() only resolves the next link.

The readlink() method providedby the Filesystem component always behaves in the same way:

  1. // returns the next direct target of the link without considering the existence of the target
  2. $filesystem->readlink('/path/to/link');
  3.  
  4. // returns its absolute fully resolved final version of the target (if there are nested links, they are resolved)
  5. $filesystem->readlink('/path/to/link', true);

Its behavior is the following:

  1. public function readlink($path, $canonicalize = false)
    • When $canonicalize is false:
      • 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 twoabsolute paths and returns the relative path from the second path to the first one:

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

mirror

mirror() copies all thecontents of the source directory into the target one (use thecopy() method to copy singlefiles):

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

isAbsolutePath

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

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

tempnam

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

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

dumpFile

dumpFile() saves the givencontents into a file. It does this in an atomic manner: it writes a temporaryfile 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 orcomplete 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 newcontents at the end of some file:

  1. $filesystem->appendToFile('logs.txt', 'Email sent to [email protected]');

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

Error Handling

Whenever something wrong happens, an exception implementingExceptionInterface orIOExceptionInterface is thrown.

Note

An IOException isthrown if directory creation fails.