PHPackages                             mycademy/yii2-file-storage - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. mycademy/yii2-file-storage

ActiveYii2-extension[Database &amp; ORM](/categories/database)

mycademy/yii2-file-storage
==========================

File storage abstraction layer for Yii2

1.3.0(4y ago)14.3k↓50%BSD-3-ClausePHP

Since Feb 10Pushed 4y agoCompare

[ Source](https://github.com/MyCademy/yii2-file-storage)[ Packagist](https://packagist.org/packages/mycademy/yii2-file-storage)[ RSS](/packages/mycademy-yii2-file-storage/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (10)Used By (0)

This extension provides a file storage abstraction layer for Yii2.

It's forked from  by [@klimov-paul](https://github.com/klimov-paul)Since the original repository has been archived, this forks aims to contignue development and keep compatibility with newer versions of it's depencies (e.g. aws-sdk-php).

For license information check the [LICENSE](LICENSE.md)-file.

[![Latest Stable Version](https://camo.githubusercontent.com/f04193ebb545703903dc27924a8aa7d631bf8b567355a6787df4ca70b278812c/68747470733a2f2f706f7365722e707567782e6f72672f6d79636164656d792f796969322d66696c652d73746f726167652f762f737461626c652e706e67)](https://packagist.org/packages/mycademy/yii2-file-storage)[![Total Downloads](https://camo.githubusercontent.com/edec2baed6a826f14a05cd0165238eed78c19e14ba3b7848ac1d2412c65473b6/68747470733a2f2f706f7365722e707567782e6f72672f6d79636164656d792f796969322d66696c652d73746f726167652f646f776e6c6f6164732e706e67)](https://packagist.org/packages/mycademy/yii2-file-storage)[![Build Status](https://camo.githubusercontent.com/bdc4a73c22fb5b9368e5ecafdbaaf1eee9b897158cd4dd814e1d91e1039b3cdb/68747470733a2f2f7472617669732d63692e6f72672f6d79636164656d792f796969322d66696c652d73746f726167652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/mycademy/yii2-file-storage)

Installation
------------

[](#installation)

The preferred way to install this extension is through [composer](http://getcomposer.org/download/).

Either run

```
php composer.phar require --prefer-dist mycademy/yii2-file-storage

```

or add

```
"mycademy/yii2-file-storage": "*"
```

to the require section of your composer.json.

If you wish to use Amazon S3 storage, you should also install [aws/aws-sdk-php](https://github.com/aws/aws-sdk-php) version 2. Either run

```
php composer.phar require --prefer-dist aws/aws-sdk-php:~2.0

```

or add

```
"aws/aws-sdk-php": "~3.172"
```

to the require section of your composer.json.

If you wish to use MongoDB storage, you should also install [yiisoft/yii2-mongodb](https://github.com/yiisoft/yii2-mongodb) version 2.1. Either run

```
php composer.phar require --prefer-dist yiisoft/yii2-mongodb:~2.1.0

```

or add

```
"yiisoft/yii2-mongodb": "2.1.0"
```

to the require section of your composer.json.

Usage
-----

[](#usage)

This extension provides file storage abstraction layer for Yii2. This abstraction introduces 2 main terms: 'storage' and 'bucket'. 'Storage' - is a unit, which is able to store files using some particular approach. 'Bucket' - is a logical part of the storage, which has own specific attributes and serves some logical mean. Each time you need to read/write a file you should do it via particular bucket, which is always belongs to the file storage.

Example application configuration:

```
return [
    'components' => [
        'fileStorage' => [
            'class' => 'mycademy\yii2filestorage\local\Storage',
            'basePath' => '@webroot/files',
            'baseUrl' => '@web/files',
            'dirPermission' => 0775,
            'filePermission' => 0755,
            'buckets' => [
                'tempFiles' => [
                    'baseSubPath' => 'temp',
                    'fileSubDirTemplate' => '{^name}/{^^name}',
                ],
                'imageFiles' => [
                    'baseSubPath' => 'image',
                    'fileSubDirTemplate' => '{ext}/{^name}/{^^name}',
                ],
            ]
        ],
        // ...
    ],
    // ...
];
```

Example usage:

```
$bucket = Yii::$app->fileStorage->getBucket('tempFiles');

$bucket->saveFileContent('foo.txt', 'Foo content'); // create file with content
$bucket->deleteFile('foo.txt'); // deletes file from bucket
$bucket->copyFileIn('/path/to/source/file.txt', 'file.txt'); // copy file into the bucket
$bucket->copyFileOut('file.txt', '/path/to/destination/file.txt'); // copy file from the bucket
var_dump($bucket->fileExists('file.txt')); // outputs `true`
echo $bucket->getFileUrl('file.txt'); // outputs: 'http://domain.com/files/f/i/file.txt'
```

Following file storages are available with this extension:

- \[\[\\mycademy\\yii2filestorage\\local\\Storage\]\] - stores files on the OS local file system.
- \[\[\\mycademy\\yii2filestorage\\sftp\\Storage\]\] - stores files using SSH2 SFTP.
- \[\[\\mycademy\\yii2filestorage\\amazon\\Storage\]\] - stores files using Amazon simple storage service (S3).
- \[\[\\mycademy\\yii2filestorage\\mongodb\\Storage\]\] - stores files using MongoDB GridFS.
- \[\[\\mycademy\\yii2filestorage\\hub\\Storage\]\] - allows combination of different file storages.

Please refer to the particular storage class for more details.

**Heads up!** Some of the storages may require additional libraries or PHP extensions, which are not required with this package by default, to be installed. Please check particular storage class documentation for the details.

Abstraction usage
------------------

[](#abstraction-usage-)

Each provided storage implements same interface for the files processing. Thus each storage can substitute another one, unless program code follows this interface. This allows you to switch between different storages without being need to adjust program source code. For example, at production server you may need to use SFTP for files storing and your application config looks like following:

```
return [
    'components' => [
        'fileStorage' => [
            'class' => 'mycademy\yii2filestorage\sftp\Storage',
            'ssh' => [
                'host' => 'file.server.com',
                'username' => 'user',
                'password' => 'some-password',
            ],
            'basePath' => '/var/www/html/files',
            'baseUrl' => 'http://file.server.com/files',
            'buckets' => [
                'temp',
                'item',
            ]
        ],
        // ...
    ],
    // ...
];
```

However, at development environment you may use simple local file storage instead:

```
return [
    'components' => [
        'fileStorage' => [
            'class' => 'mycademy\yii2filestorage\local\Storage',
            'basePath' => '@webroot/files',
            'baseUrl' => '@web/files',
            'buckets' => [
                'temp',
                'item',
            ]
        ],
        // ...
    ],
    // ...
];
```

You can specify a bucket name that is different from the internal name. In the following example the bucket is retrieved with `Wii::$app->fileStorage->getBucket('images');`but will be stored in the `my-image-bucket` bucket.

```
return [
    'components' => [
        'fileStorage' => [
            'class' => 'mycademy\yii2filestorage\amazon\Storage',
            'buckets' => [
                'buckets' => [
                    'images' => [
                        'name' => 'my-image-bucket',
                        'region' => 'us-west-1',
                    ],
                ],
            ]
        ],
        // ...
    ],
    // ...
];
```

You can also combine several different storages using \[\[\\mycademy\\yii2filestorage\\hub\\Storage\]\], if necessary:

```
return [
    'components' => [
        'fileStorage' => [
            'class' => 'mycademy\yii2filestorage\hub\Storage',
            'storages' => [
                [
                    'class' => 'mycademy\yii2filestorage\sftp\Storage',
                    'ssh' => [
                        'host' => 'file.server.com',
                        'username' => 'user',
                        'password' => 'some-password',
                    ],
                    'basePath' => '/var/www/html/files',
                    'baseUrl' => 'http://file.server.com/files',
                    'buckets' => [
                        'item',
                    ]
                ],
                [
                    'class' => 'mycademy\yii2filestorage\local\Storage',
                    'basePath' => '@webroot/files',
                    'baseUrl' => '@web/files',
                    'buckets' => [
                        'temp',
                    ]
                ]
            ],
        ],
        // ...
    ],
    // ...
];
```

Accessing files by URL
-----------------------

[](#accessing-files-by-url-)

Almost all file storage implementation, implemented in this extension, provide mechanism for accessing stored files via web URL. Actual mechanism implementation may vary depending on particular storage. For example: \[\[\\mycademy\\yii2filestorage\\local\\Storage\]\] allows setup of the URL leading to its root folder, creating URL for particular file appending its name to base URL, while \[\[\\mycademy\\yii2filestorage\\amazon\\Storage\]\] uses S3 built-in object URL composition.

In order to get URL leading to the stored file, you should use \[\[\\mycademy\\yii2filestorage\\BucketInterface::getFileUrl()\]\] method:

```
$bucket = Yii::$app->fileStorage->getBucket('tempFiles');

$fileUrl = $bucket->getFileUrl('image.jpg');
```

In case particular storage does not provide native URL file access, or it is not available or not desirable by some reason, you can setup composition of the file URL via Yii URL route mechanism. You need to setup `baseUrl` to be an array, containing route, which leads to the Yii controller action, which will return the file content. For example:

```
return [
    'components' => [
        'fileStorage' => [
            'class' => 'mycademy\yii2filestorage\local\Storage',
            'baseUrl' => ['/file/download'],
            // ...
        ],
        // ...
    ],
    // ...
];
```

With this configuration `getFileUrl()` method will use current application URL manager to create URL. Doing so it will add bucket name as `bucket` parameter and file name as `filename` parameter. For example:

```
use yii\helpers\Url;

$bucket = Yii::$app->fileStorage->getBucket('images');

$fileUrl = $bucket->getFileUrl('logo.png');
$manualUrl = Url::to(['/file/download', 'bucket' => 'images', 'filename' => 'logo.png']);
var_dump($fileUrl === $manualUrl); // outputs `true`
```

You may setup \[\[\\mycademy\\yii2filestorage\\DownloadAction\]\] to handle file content web access. For example:

```
class FileController extends \yii\web\Controller
{
    public function actions()
    {
        return [
            'download' => [
                'class' => 'mycademy\yii2filestorage\DownloadAction',
            ],
        ];
    }
}
```

> Tip: usage of the controller action for the file web access usually slower then native mechanism provided by file storage, however, you may put some extra logic into it, like allowing file access for logged in users only.

Processing of the large files
------------------------------

[](#processing-of-the-large-files-)

Saving or reading large files, like &gt; 100 MB, using such methods like \[\[\\mycademy\\yii2filestorage\\BucketInterface::saveFileContent()\]\] or \[\[\\mycademy\\yii2filestorage\\BucketInterface::getFileContent()\]\], may easily exceed PHP memory limit, breaking the script. You should use \[\[\\mycademy\\yii2filestorage\\BucketInterface::openFile()\]\] method to create a file resource similar to the one created via \[\[fopen()\]\] PHP function. Such resource can be read or written by blocks, keeping memory usage low. For example:

```
$bucket = Yii::$app->fileStorage->getBucket('tempFiles');

$resource = $bucket->openFile('new_file.dat', 'w');
fwrite($resource, 'content part1');
fwrite($resource, 'content part2');
// ...
fclose($resource);

$resource = $bucket->openFile('existing_file.dat', 'r');
while (!feof($resource)) {
    echo fread($resource, 1024);
}
fclose($resource);
```

> Note: You should prefer usage of simple modes like `r` and `w`, avoiding complex ones like `w+`, as they may be not supported by some storages.

Logging
--------

[](#logging-)

Each file operation performed by file storage component is logged. In order to setup a log target, which can capture all entries related to file storage, you should use category `mycademy\yii2filestorage\*`. For example:

```
return [
    // ...
    'components' => [
        // ...
        'log' => [
            // ...
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'logFile' => '@runtime/logs/file-storage.log',
                    'categories' => ['mycademy\yii2filestorage\*'],
                ],
                // ...
            ],
        ],
    ],
];
```

###  Health Score

34

—

LowBetter than 77% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 65.2% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~265 days

Recently: every ~403 days

Total

9

Last Release

1619d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/13200128?v=4)[MyCademy](/maintainers/MyCademy)[@MyCademy](https://github.com/MyCademy)

---

Top Contributors

[![klimov-paul](https://avatars.githubusercontent.com/u/1482054?v=4)](https://github.com/klimov-paul "klimov-paul (43 commits)")[![rhertogh](https://avatars.githubusercontent.com/u/1292337?v=4)](https://github.com/rhertogh "rhertogh (20 commits)")[![leandrogehlen](https://avatars.githubusercontent.com/u/1750751?v=4)](https://github.com/leandrogehlen "leandrogehlen (2 commits)")[![vuongxuongminh](https://avatars.githubusercontent.com/u/38932626?v=4)](https://github.com/vuongxuongminh "vuongxuongminh (1 commits)")

---

Tags

abstractionamazons3sshsftpfilestoragemongodbyii2GridFS

### Embed Badge

![Health badge](/badges/mycademy-yii2-file-storage/health.svg)

```
[![Health](https://phpackages.com/badges/mycademy-yii2-file-storage/health.svg)](https://phpackages.com/packages/mycademy-yii2-file-storage)
```

###  Alternatives

[league/flysystem

File storage abstraction for PHP

13.6k639.1M2.2k](/packages/league-flysystem)[creocoder/yii2-flysystem

The flysystem extension for the Yii framework

2931.7M62](/packages/creocoder-yii2-flysystem)[mostafaznv/larupload

Larupload is a ORM based file uploader for laravel to upload image, video, audio and other known files.

73403.7k3](/packages/mostafaznv-larupload)[linkorb/objectstorage

ObjectStorage library for your cloud-based applications

105.4k6](/packages/linkorb-objectstorage)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
