# Introducing GetFiles for Craft CMS

Source: https://jonleverrier.com/notes/introducing-getfiles-for-craft-cms
Published: 2020-05-11
Topics: Development

A utility plugin that retrieves a list of files from a specified folder for Craft CMS.

## Introduction

GetFiles was first launched in February 2019. It retrieves a list of files from a specified folder.

### Requirements

- Craft 3.1 or above
- You need a simple way of retrieving files which are not managed by Craft

## Examples

### List the contents of a directory

Inside /assets/images there are 3 image files:

```shell
22 Apr 22:54 image01.jpg
22 Apr 22:54 image02.jpg
22 Apr 22:54 image03.gif
```

In Twig we pass an array of settings into GetFiles. The settings array contains the path of the folder to list:

```twig
{% set settings =
    {
        path: '/assets/images/'
    }
%}
{% set images = craft.getfiles.config(settings) %}

<p>Available images:</p>
{% for image in images %}
    <img src="{{ image }}" alt="Image {{ loop.index }}">
{% endfor %}
```

This would output:

```html
<img src="/assets/images/image01.jpg" alt="Image 1">
<img src="/assets/images/image02.jpg" alt="Image 2">
<img src="/assets/images/image03.gif" alt="Image 3">
```

### List the contents of a directory which matches a regex pattern

Inside /assets/images there are 3 files:

```html
22 Apr 22:54 image01.jpg
22 Apr 22:54 image02.jpg
22 Apr 22:54 image03.gif
```

In Twig we pass an array of settings into GetFiles. The settings array contains the path of the folder to list and a regex pattern to match:

```twig
{% set settings =
    {
        path: '/assets/images/',
        pattern: '*.gif'
    }
%}
{% set images = craft.getfiles.config(settings) %}

<p>Available images:</p>
{% for image in images %}
<img src="/assets/images/{{ image }}" alt="Image {{ loop.index }}">
{% endfor %}
```

This would output:

```html
<p>Available images:<p>
<img src="/assets/images/image03.gif" alt="Image 1">
```

## Configuration

#### path

```plaintext
string, required
```

A valid folder for GetFiles to search

#### pattern

```plaintext
string, optional, default value '*'
```

A regex pattern to match

#### pathformat

```plaintext
string, optional, default value '2' 
```

1. Filename only
2. Filename relative to your base path (default value)
3. Absolute path to the filename

```twig
{% set myVarSettings =
    {
        path: '<path>',
        pathformat: '<pathformat>',
        pattern: '<pattern>'
    }
%}

{% set myVar = craft.getfiles.config(myVarSettings) %}
```

## Installation

```shell
composer require youandmedigital/craft-getfiles
```

If you have any issues, feedback or ideas, please feel free to [submit an issue](https://github.com/youandmedigital/craft-getfiles/issues/new) on [Github](https://github.com/youandmedigital/craft-getfiles).
