1. Code
  2. PHP

How to Use the Symfony Filesystem Component

Scroll to top

In this article, we're going to explore the Symfony Filesystem component, which provides useful methods to interact with a file system. After installation and configuration, we'll create a few real-world examples of how to use it.

The Symfony Filesystem Component

More often than not, you'll need to interact with a file system if you're dealing with PHP applications. In most cases, you either end up using the core PHP functions or create your own custom wrapper class to achieve the desired functionality. Either way, it's difficult to maintain over a longer period of time. So what you need is a library which is well maintained and easy to use. That's where the Symfony Filesystem component comes in.

The Symfony Filesystem component provides useful wrapper methods that make the file system interaction a breeze and a fun experience. Let's quickly look at what it's capable of:

  • creating a directory
  • creating a file
  • editing file contents
  • changing the owner and group of a file or directory
  • creating a symlink
  • copying a file or directory
  • removing a file or directory
  • and more

In this article, I'll show you how to unleash the power of the Symfony Filesystem component. As usual, we'll start with installation and configuration instructions, and then we'll implement a few real-world examples to demonstrate the key concepts.

Installation and Configuration

In this section, we're going to install the Symfony Filesystem component. I assume that you've already installed Composer in your system as we'll need it to install the Filesystem component available at Packagist.

So go ahead and install the Filesystem component using the following command.

1
$composer require symfony/filesystem

That should have created a composer.json file, which should look like this:

1
{
2
    "require": {
3
        "symfony/filesystem": "^4.1"
4
    }
5
}

So that's the installation part, but how are you supposed to use it? In fact, it's just a matter of including the autoload.php file created by Composer in your application, as shown in the following snippet.

1
<?php
2
require_once './vendor/autoload.php';
3
4
// application code

5
?>

A Real-World Example

In this section, we'll create an example which demonstrates how you could use the Filesystem component in your applications to perform various filesystem operations.

To start with, let's go ahead and create the index.php file with the following contents.

1
<?php
2
require_once './vendor/autoload.php';
3
4
use Symfony\Component\Filesystem\Filesystem;
5
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
6
7
// init file system

8
$fsObject = new Filesystem();
9
$current_dir_path = getcwd();
10
11
// make a new directory

12
// create a new file and add contents

13
// copy a directory

14
// remove a directory

Here, we've initialized the Filesystem object to $fsObject and saved the current directory to $current_dir_path. In the upcoming sections, we'll use $fsObject to perform different operations.

Make a New Directory

First, we'll create a new directory.

1
//make a new directory

2
try {
3
    $new_dir_path = $current_dir_path . "/foo";
4
5
    if (!$fsObject->exists($new_dir_path))
6
    {
7
        $old = umask(0);
8
        $fsObject->mkdir($new_dir_path, 0775);
9
        $fsObject->chown($new_dir_path, "www-data");
10
        $fsObject->chgrp($new_dir_path, "www-data");
11
        umask($old);
12
    }
13
} catch (IOExceptionInterface $exception) {
14
    echo "Error creating directory at". $exception->getPath();
15
}

Here, we've used the exists method to check if the foo directory already exists before creating it.

Next, we used the mkdir method to create the foo directory with the 0775 permissions, which means readable and executable by all, but only writable by the file owner and their group. (This is the octal notation for filesystem permissions—to learn more, check out this breakdown of octal notation.) Further, we've used the chown and chgrp methods to change the owner and group of the foo directory.

Create a New File and Add Contents

In this section, we'll create a new file and add contents to that file.

1
// create a new file and add contents

2
try {
3
    $new_file_path = $current_dir_path . "/foo/bar.txt";
4
5
    if (!$fsObject->exists($new_file_path))
6
    {
7
        $fsObject->touch($new_file_path);
8
        $fsObject->chmod($new_file_path, 0777);
9
        $fsObject->dumpFile($new_file_path, "Adding dummy content to bar.txt file.\n");
10
        $fsObject->appendToFile($new_file_path, "This should be added to the end of the file.\n");
11
    }
12
} catch (IOExceptionInterface $exception) {
13
    echo "Error creating file at". $exception->getPath();
14
}

Here, we've used the touch method to create a new file and then used chmod to set its permissions to 0777—globally readable, writable, and executable.

Once the file is created, you can use the dumpFile method to add contents to that file. On the other hand, if you want to add contents to the existing file, you can use the appendToFile method, as shown in the above example.

Copy a Directory

So far, we've created the foo directory and the bar.txt file using the $fsObject object. In this section, we'll see how to copy a directory along with the contents.

1
//copy a directory

2
try {
3
    $src_dir_path = $current_dir_path . "/foo";
4
    $dest_dir_path = $current_dir_path . "/foo_copy";
5
6
    if (!$fsObject->exists($dest_dir_path))
7
    {
8
        $fsObject->mirror($src_dir_path, $dest_dir_path);
9
    }
10
} catch (IOExceptionInterface $exception) {
11
    echo "Error copying directory at". $exception->getPath();
12
}

As you can see, first we built the path names with string concatenation. Then, once we made sure the directory didn't already exist using the exists method, we used the mirror method to copy the foo directory into the foo_copy directory.

Remove a Directory

Finally, let's see how to remove a directory.

1
//remove a directory

2
try {
3
    $arr_dirs = array(
4
        $current_dir_path . "/foo",
5
        $current_dir_path . "/foo_copy"
6
    );
7
8
    $fsObject->remove($arr_dirs);
9
} catch (IOExceptionInterface $exception) {
10
    echo "Error deleting directory at". $exception->getPath();
11
}

Again, it's pretty straightforward—to delete a directory, you just use the remove method.

You can find the complete code for index.php in our GitHub repo.

Conclusion

So that's a brief introduction to the Symfony Filesystem component. The Symfony Filesystem component provides methods that make interaction with a file system a breeze. We looked at how to install the component, and we created a handful of examples to demonstrate various aspects of the component.

Post thumbnail generated by OpenAI DALL-E.

This post has been updated with contributions from Sajal Soni. Sajal belongs to India, and he loves to spend time creating websites based on open-source frameworks.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.