Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • SensioLabs Professional services to help you with Symfony
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by SensioLabs
  1. Home
  2. Documentation
  3. Components
  4. The Finder Component
  • Documentation
  • Book
  • Reference
  • Bundles
  • Cloud

Table of Contents

  • Installation
  • Usage
  • Criteria
    • Location
    • Files or Directories
    • Sorting
    • File Name
    • File Contents
    • Path
    • File Size
    • File Date
    • Directory Depth
    • Custom Filtering
    • Reading Contents of Returned Files

The Finder Component

Edit this page

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

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

The Finder Component

The Finder component finds files and directories via an intuitive fluent interface.

Installation

You can install the component in 2 different ways:

  • Install it via Composer (symfony/finder on Packagist);
  • Use the official Git repository (https://github.com/symfony/finder).

Then, require the vendor/autoload.php file to enable the autoloading mechanism provided by Composer. Otherwise, your application won't be able to find the classes of this Symfony component.

Usage

The Finder class finds files and/or directories:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in(__DIR__);

foreach ($finder as $file) {
    // Dump the absolute path
    var_dump($file->getRealPath());

    // Dump the relative path to the file, omitting the filename
    var_dump($file->getRelativePath());

    // Dump the relative path to the file
    var_dump($file->getRelativePathname());
}

The $file is an instance of SplFileInfo which extends PHP's own SplFileInfo to provide methods to work with relative paths.

The above code prints the names of all the files in the current directory recursively. The Finder class uses a fluent interface, so all methods return the Finder instance.

Tip

A Finder instance is a PHP Iterator. So, instead of iterating over the Finder with foreach, you can also convert it to an array with the iterator_to_array method, or get the number of items with iterator_count.

Caution

When searching through multiple locations passed to the in() method, a separate iterator is created internally for every location. This means we have multiple result sets aggregated into one. Since iterator_to_array uses keys of result sets by default, when converting to an array, some keys might be duplicated and their values overwritten. This can be avoided by passing false as a second parameter to iterator_to_array.

Criteria

There are lots of ways to filter and sort your results.

Location

The location is the only mandatory criteria. It tells the finder which directory to use for the search:

1
$finder->in(__DIR__);

Search in several locations by chaining calls to in():

1
2
3
4
5
// search inside *both* directories
$finder->files()->in(array(__DIR__, '/elsewhere'));

// same as above
$finder->in(__DIR__)->in('/elsewhere');

Use wildcard characters to search in the directories matching a pattern:

1
$finder->in('src/Symfony/*/*/Resources');

Each pattern has to resolve to at least one directory path.

Exclude directories from matching with the exclude() method:

1
$finder->in(__DIR__)->exclude('ruby');

It's also possible to ignore directories that you don't have permission to read:

1
$finder->ignoreUnreadableDirs()->in(__DIR__);

As the Finder uses PHP iterators, you can pass any URL with a supported protocol:

1
$finder->in('ftp://example.com/pub/');

And it also works with user-defined streams:

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Finder\Finder;

$s3 = new \Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper('s3');

$finder = new Finder();
$finder->name('photos*')->size('< 100K')->date('since 1 hour ago');
foreach ($finder->in('s3://bucket-name') as $file) {
    // ... do something with the file
}

Note

Read the Streams documentation to learn how to create your own streams.

Files or Directories

By default, the Finder returns files and directories; but the files() and directories() methods control that:

1
2
3
$finder->files();

$finder->directories();

If you want to follow links, use the followLinks() method:

1
$finder->files()->followLinks();

By default, the iterator ignores popular VCS files. This can be changed with the ignoreVCS() method:

1
$finder->ignoreVCS(false);

Sorting

Sort the result by name or by type (directories first, then files):

1
2
3
$finder->sortByName();

$finder->sortByType();

Note

Notice that the sort* methods need to get all matching elements to do their jobs. For large iterators, it is slow.

You can also define your own sorting algorithm with sort() method:

1
2
3
4
5
6
$sort = function (\SplFileInfo $a, \SplFileInfo $b)
{
    return strcmp($a->getRealPath(), $b->getRealPath());
};

$finder->sort($sort);

File Name

Restrict files by name with the name() method:

1
$finder->files()->name('*.php');

The name() method accepts globs, strings, or regexes:

1
$finder->files()->name('/\.php$/');

The notName() method excludes files matching a pattern:

1
$finder->files()->notName('*.rb');

File Contents

Restrict files by contents with the contains() method:

1
$finder->files()->contains('lorem ipsum');

The contains() method accepts strings or regexes:

1
$finder->files()->contains('/lorem\s+ipsum$/i');

The notContains() method excludes files containing given pattern:

1
$finder->files()->notContains('dolor sit amet');

Path

Restrict files and directories by path with the path() method:

1
2
3
4
// matches files that contain "data" anywhere in their paths (files or directories)
$finder->path('data');
// for example this will match data/*.xml and data.xml if they exist
$finder->path('data')->name('*.xml');

On all platforms slash (i.e. /) should be used as the directory separator.

The path() method accepts a string or a regular expression:

1
2
$finder->path('foo/bar');
$finder->path('/^foo\/bar/');

Internally, strings are converted into regular expressions by escaping slashes and adding delimiters:

1
2
dirname    ===>    /dirname/
a/b/c      ===>    /a\/b\/c/

The notPath() method excludes files by path:

1
$finder->notPath('other/dir');

File Size

Restrict files by size with the size() method:

1
$finder->files()->size('< 1.5K');

Restrict by a size range by chaining calls:

1
$finder->files()->size('>= 1K')->size('<= 2K');

The comparison operator can be any of the following: >, >=, <, <=, ==, !=.

The target value may use magnitudes of kilobytes (k, ki), megabytes (m, mi), or gigabytes (g, gi). Those suffixed with an i use the appropriate 2**n version in accordance with the IEC standard.

File Date

Restrict files by last modified dates with the date() method:

1
$finder->date('since yesterday');

The comparison operator can be any of the following: >, >=, <, <=, ==. You can also use since or after as an alias for >, and until or before as an alias for <.

The target value can be any date supported by the strtotime function.

Directory Depth

By default, the Finder recursively traverse directories. Restrict the depth of traversing with depth():

1
2
$finder->depth('== 0');
$finder->depth('< 3');

Custom Filtering

To restrict the matching file with your own strategy, use filter():

1
2
3
4
5
6
7
8
$filter = function (\SplFileInfo $file)
{
    if (strlen($file) > 10) {
        return false;
    }
};

$finder->files()->filter($filter);

The filter() method takes a Closure as an argument. For each matching file, it is called with the file as a SplFileInfo instance. The file is excluded from the result set if the Closure returns false.

Reading Contents of Returned Files

The contents of returned files can be read with getContents():

1
2
3
4
5
6
7
8
9
10
use Symfony\Component\Finder\Finder;

$finder = new Finder();
$finder->files()->in(__DIR__);

foreach ($finder as $file) {
    $contents = $file->getContents();

    // ...
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    We stand with Ukraine.
    Version:
    Take the exam at home

    Take the exam at home

    Symfony Code Performance Profiling

    Symfony Code Performance Profiling

    Symfony footer

    ↓ Our footer now uses the colors of the Ukrainian flag because Symfony stands with the people of Ukraine.

    Avatar of Adam Lee Conlin, a Symfony contributor

    Thanks Adam Lee Conlin (@hades200082) for being a Symfony contributor

    1 commit • 8 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • Symfony at a Glance
      • Symfony Components
      • Case Studies
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • SymfonyConnect
      • Support
      • How to be Involved
      • Code of Conduct
      • Events & Meetups
      • Projects using Symfony
      • Downloads Stats
      • Contributors
      • Backers
    • Blog

      • Events & Meetups
      • A week of symfony
      • Case studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Documentation
      • Living on the edge
      • Releases
      • Security Advisories
      • SymfonyInsight
      • Twig
      • SensioLabs
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Deployed on

    Follow Symfony

    Search by Algolia