PHPackages                             aminyazdanpanah/handling-file-uploads - 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. [File &amp; Storage](/categories/file-storage)
4. /
5. aminyazdanpanah/handling-file-uploads

AbandonedArchivedLibrary[File &amp; Storage](/categories/file-storage)

aminyazdanpanah/handling-file-uploads
=====================================

Easily save all your uploaded files into your path directory and extract their info

v1.1.14(6y ago)3413MITPHPPHP ^7.1

Since Feb 15Pushed 5y ago1 watchersCompare

[ Source](https://github.com/aminyazdanpanah/handling-file-uploads)[ Packagist](https://packagist.org/packages/aminyazdanpanah/handling-file-uploads)[ RSS](/packages/aminyazdanpanah-handling-file-uploads/feed)WikiDiscussions master Synced today

READMEChangelog (6)Dependencies (2)Versions (8)Used By (0)

Handling File Uploads
=====================

[](#handling-file-uploads)

[![Build Status](https://camo.githubusercontent.com/80fdab15156402820e592e733b68fc5ecd67252edd26ea0f3ef8b6b844a240f2/68747470733a2f2f7472617669732d63692e6f72672f616d696e79617a64616e70616e61682f68616e646c696e672d66696c652d75706c6f6164732e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/aminyazdanpanah/handling-file-uploads)[![Latest Version on Packagist](https://camo.githubusercontent.com/29701ce4ee9202d028495b2062453f1f937ef03a8e93776ce9af562c707105a2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f616d696e79617a64616e70616e61682f68616e646c696e672d66696c652d75706c6f6164732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/aminyazdanpanah/handling-file-uploads)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/0af2dd4c779a735e0a37ad76ea32cd663982d8ea75025154ae32e46bdf14ca99/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f616d696e79617a64616e70616e61682f68616e646c696e672d66696c652d75706c6f6164732f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/aminyazdanpanah/handling-file-uploads/?branch=master)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/aminyazdanpanah/PHP-FFmpeg-video-streaming/blob/master/LICENSE)[![Code Intelligence Status](https://camo.githubusercontent.com/b7c9ae9aac45e2641ed4659884082c63664e53fef9a0535214bd72d7e2bec70c/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f616d696e79617a64616e70616e61682f68616e646c696e672d66696c652d75706c6f6164732f6261646765732f636f64652d696e74656c6c6967656e63652e7376673f623d6d6173746572)](https://scrutinizer-ci.com/code-intelligence)[![Total Downloads](https://camo.githubusercontent.com/56f70dbfc6a37be2dbfebfb985ba9a7fd6f1e0f4fd060304ae4b9fd1a8e246bc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f616d696e79617a64616e70616e61682f68616e646c696e672d66696c652d75706c6f6164732e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/aminyazdanpanah/handling-file-uploads)

Handles multiple uploads with a powerful validation for images, videos, audios, and archive files. This package allows you to handle your file after your file was uploaded. You can resize, convert, extract and so many things to do after your files were uploaded. At the end, you can extract details of files into an `array`.

Features
--------

[](#features)

- Upload multiple files with a configuration variable.
- validate your videos, audios, images, archive files with different rules.
- Manage your files such as converting, resizing, extracting and so many things to do after your files were uploaded.
- Export the details of files into an array and you can easily insert them into a database.
- Compatible with PHP &gt;= 7.1.0.

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

[](#installation)

This version of the package is only compatible with PHP 7.1.0 and later.

Install the package via composer:

```
composer require aminyazdanpanah/handling-file-uploads
```

Basic Usage
-----------

[](#basic-usage)

```
require_once 'vendor/autoload.php';

$export = function($filename){
	//Add additional validators and handle file after your file was uploaded.
    //...
}
```

##### upload multiple files

[](#upload-multiple-files)

```
$config_files = [
    [
        'name' => 'upload_key_name', //The key name that you send your file to the server
        'save_to' => $output_path, //The path you'd like to save your file(auto make new directory)
        'validator' => [
                'min_size' => 100, //Minimum size is 100KB
                'max_size' => 1024 * 2, //Maximum size is 2MB
                'allowed_extensions' => ['jpg', 'jpeg', 'png', ...] //Just images are allowed
        ],
        'export' => $export //Get a callback method(whatever you want to do with  your file after it was uploaded!)
    ],
    [
        //...
    ],
];

$uploads = uploads($config_files)->all();

var_dump("", $uploads, "");
```

##### upload a single files

[](#upload-a-single-files)

```
$validator = new Validator();

$validator = $validator->setMinSize(100)
    ->setMaxSize(1024 * 2)
    ->setType(['jpg', 'png', 'jpeg']);

$upload = new File();

$upload = $upload->file('upload_key_name')
    ->setValidator($validator)
    ->setOverride(false)
    ->setSaveAs('my_dfile')
    ->save($output_path, $export);

var_dump("", $upload, "");
```

**Important: Please see [examples](https://github.com/aminyazdanpanah/handling-file-uploads/blob/master/examples/) for more information. In these pages you can see complete examples of usage this package.**

Documentation
-------------

[](#documentation)

It is recommended to browse the source code as it is self-documented.

### Configuration

[](#configuration)

In the sever side you should create an array of config and pass it to `uploads()` method:

```
$config_files = [
    [
        'name' => 'upload_image',
        'save_to' => __DIR__ . "/images/user/" . time(),
        'validator' => [
            'min_size' => 100,
            'max_size' => 2048,
            'types' => ['jpg', 'jpeg', 'png']
        ]
    ],
    [
        //...
    ],
];

$uploads = Upload::files($config_files);
```

For more information about these attributes, please check the below tables:

##### Attributes of array of config

[](#attributes-of-array-of-config)

attrdefaultmeanname**mandatory:** must be specifiedThe key name you send your file to the server-PHP($\_Files).save\_to**mandatory:** must be specifiedThe path that you would like to save your file in the server or computer.save\_asBase file nameThe name that you want to save.overridefalseOverride original file with the same filename.validatorno rulesValidate your file before save(see validator table).exportNothing happensA callback method that you specify additional rules and manage your file after it was uploaded.### Validation

[](#validation)

#### Before Saving

[](#before-saving)

You can validate your uploaded file before move the uploaded file to the destination. There are some rules that you can apply on your file:

##### Attributes of validator

[](#attributes-of-validator)

attrdefaultmeanmin\_size1The minimum size of files that are allowed (KiloByte).max\_size999999The maximum size of files that are allowed (KiloByte).types'\*' (everything)The types that are allowed (must be an array)#### After Saving

[](#after-saving)

You can set some rules after move the uploaded file to the destination by using a callback method. To validate a file after saving, just check your file in the callback method and throw an `AYazdanpanah\SaveUploadedFiles\Exception\Exception`. In the end, put it in the array of config and pass it to `Upload::files($config)`. In the callback method, you can manage your file. For example, resize image or video, convert video, extracting an archive file and etc. After that, you are able to return your data.

```
$export = function ($filename) {

    //Add a  Validator: if $filename is not ...
    if (//condition 1) {
        throw new Exception("Exception 1");
    }

    //Add a  Validator: if $filename is not ...
    if (//condition 2) {
        throw new Exception("Exception 2");
    }
    //...

    //Handles file: resize image or video, convert video, extracting the archive and etc.
    //...

    //return whatever you want
    return $data;
}

$config = [
    [
        //... ,
        'export' => $export
    ],
];

Upload::files($config);
```

##### Validate and Manage a Video file

[](#validate-and-manage-a-video-file)

There are some factors that can use to validate a video. I recommended [PHP-FFMpeg-video-streaming](https://github.com/aminyazdanpanah/PHP-FFmpeg-video-streaming) package that is a wrapper around [PHP-FFmpeg](https://github.com/PHP-FFMpeg/PHP-FFMpeg). You can validate your video by using its codec, duration, width, height, ratio, and other its attributes. After that, depends on whether your file is valid or not, you can throw an `Exception`. At the end, as it can be seen below, you can convert your video or whatever you want to do with your file and export your data:

```
$video_path = __DIR__ . "/videos/$user_id";
$video_name = str_random();
$export_video = function ($filename) use ($video_path, $video_name) {

    $video = AYazdanpanah\FFMpegStreaming\FFMpeg::create()
        ->open($filename);

    //Extracting video meta data
    $video_metadata = $video->getFirstStream();

    //Add a  Validator: check if the file is video and video duration is not longer than 1 minute
    if (!$video_metadata->isVideo() && null === ($duration = $video_metadata->get('duration')) && $duration >= 60) {
        throw new Exception("Your file is not a video or your video duration is longer than 1 minute!");
    }

    //Add a  Validator: check if the video is HD or higher resolution
    if ($video_metadata->get('width',1) * $video_metadata->get('height', 1) < 1280 * 720) {
        throw new Exception("Sorry, your video must be at least HD or higher resolution");
    }

    //Add a  Validator: check if the video ratio is 16 / 9
    if ($video_metadata->getDimensions()->getRatio()->getValue() == 16 / 9) {
        throw new Exception("Sorry, the video ratio must be 16 / 9");
    }

    //Extracting image and resize it
    $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(intval($duration / 4)))->save("$video_path/screenshots.jpg");
    $image = new ImageResize("$video_path/screenshots.jpg");
    $image->resizeToWidth(240)->save("$video_path/{$video_name}_screenshots_small.jpg");

    //Extracting gif
    $video->gif(FFMpeg\Coordinate\TimeCode::fromSeconds(3), new FFMpeg\Coordinate\Dimension(240, 95), 3)
        ->save("$video_path/{$video_name}_animation.gif");

    //Create the dash files(it is better to create a job and dispatch it-do it in the background)
    mkdir("$video_path/dash/$video_name", 0777, true);
    dash($filename, "$video_path/dash/$video_name/output.mpd", function ($audio, $format, $percentage) {
        echo "$percentage % is transcoded\n";
    });

    //Delete the original file
    @unlink($filename);

    return $video_metadata->all();
};
```

For more information, please read [PHP FFMPEG Video Streaming documentation](https://github.com/aminyazdanpanah/PHP-FFmpeg-video-streaming) and [php-ffmpeg documentation](https://github.com/PHP-FFMpeg/PHP-FFMpeg#documentation).

##### Validate and Manage an image file

[](#validate-and-manage-an-image-file)

To validate and manage an image, I recommended [php-image-resize](https://github.com/gumlet/php-image-resize) package. For more information I strongly recommand to read [php-image-resize documantation](https://gumlet.github.io/php-image-resize/class-Gumlet.ImageResize.html) . After that, depends on whether your file is valid or not, you can throw an `Exception`. At the end, you can export your data:

```
$image_path = __DIR__ . "/images/user/$user_id";
$export_image = function ($filename) use ($image_path) {
    //Add a  Validator: check if the file is image
    if (!is_type("image", $filename)) {
        throw new Exception("Your file is not an image!");
    }

    $image_metadata = exif_read_data($filename);

    //Add a  Validator: check whether the image is square or not
    if ($image_metadata['COMPUTED']['Width'] / $image_metadata['COMPUTED']['Height'] != 1) {
        throw new Exception("Your image must be square!");
    }

    if (!is_dir($image_path . "/thumbnail")) {
        mkdir($image_path . "/thumbnail", 0777, true);
    }

    // Resize and crop your image
    $image = new ImageResize($filename);
    $image->resizeToWidth(50)->save($image_path . "/thumbnail/thumb_50.jpg");
    $image->resizeToWidth(100)->save($image_path . "/thumbnail/thumb_100.jpg");
    $image->resizeToWidth(240)->save($image_path . "/thumbnail/thumb_240.jpg");
    $image->resizeToBestFit(500, 300)->save($image_path . "/thumbnail/thumb_500_300.jpg");
    $image->crop(200, 200)->save($image_path . "/thumbnail/thumb_crop_200_200.jpg");

    return $image_metadata;
};
```

##### Validate and Manage an archive file

[](#validate-and-manage-an-archive-file)

To validate and manage an archive file, I recommended using [UnifiedArchive](https://github.com/wapmorgan/UnifiedArchive) package. For more information I strongly recommand to read [UnifiedArchive documantation](https://github.com/wapmorgan/UnifiedArchive) . After that, depends on whether your file is valid or not, you can throw an `Exception`. At the end, you can export your data:

```
$archive_path = __DIR__ . "/archive/$user_id";
$archive_name = str_random();
$archive_export = function ($filename) use ($archive_path, $archive_name) {
    mkdir("$archive_path/$archive_name");
    $archive = UnifiedArchive::open($filename);

    //Add a  Validator: check whether the file is able to open or not
    if (null === $archive) {
        unlink($filename);
        throw new Exception("Sorry!we could not open the archive.
         Please check whether your extension has been installed or not.
         Your file may be corrupted or is encrypted");
    }

    //Add a  Validator: check whether the profile.jpg is in archive or not
    if (!$archive->isFileExists('profile.jpg')) {
        unlink($filename);
        throw new Exception("Sorry!we could not find 'profile.jpg' in the archive");
    }

    //Extracting files
    $archive->extractFiles("$archive_path/$archive_name");

    return $archive->getFileNames();
};
```

##### Validate and Manage an audio file

[](#validate-and-manage-an-audio-file)

To validate and manage an archive file, I recommended using [php-ffmpeg](https://github.com/PHP-FFMpeg/PHP-FFMpeg) package. For more information I strongly recommand to read [php-ffmpeg](https://github.com/PHP-FFMpeg/PHP-FFMpeg) . After that, depends on whether your file is valid or not, you can throw an `Exception`. At the end, you can export your data:

```
$audio_path = __DIR__ . "/audios/$user_id";
$audio_name = str_random();
$audio_export = function ($filename) use ($audio_path, $audio_name) {
    mkdir($audio_path . '/flac');
    $audio = AYazdanpanah\FFMpegStreaming\FFMpeg::create()
        ->open($filename);
    $audio_metadata = $audio->getFirstStream();

    //Add a  Validator: check if the file is audio
    if (!$audio_metadata->isAudio() && null === ($duration = $audio_metadata->get('duration')) && $duration get('codec_name'), 'mp3')) {
        throw new Exception("Sorry, your audio format must be mp3!");
    }

    //Convert the file into flac format
    $format = new FFMpeg\Format\Audio\Flac();

    $format->on('progress', function ($audio, $format, $percentage) {
        echo "$percentage % transcoded\n";
    });

    $format
        ->setAudioChannels(2)
        ->setAudioKiloBitrate(256);

    $audio->save($format, "$audio_path/flac/$audio_name.flac");

    return $audio_metadata->all();
};
```

### Exporting Data

[](#exporting-data)

After uploading, class return an object that is instance of `Filter`. You can export all details of your upload by using `all()` method:

```
print_r($uploads->all());// Returns all uploads and their details.
```

##### Other possible methods

[](#other-possible-methods)

```
print_r($uploads->get(['upload_video', 'upload_raw']));// Returns specified uploads and their details.
print_r($uploads->except(['upload_raw', 'upload_image']));// Returns all uploads and their details except those ones specified.
print_r($uploads->first());// Returns first upload and it's detail.
print_r($uploads->succeeded());// Returns all succeeded uploads and their details.
print_r($uploads->failed());// Returns all failed uploads and their details.
print_r($uploads->names());// Returns all upload names.
print_r($uploads->count());// Returns the number of uploads
```

Examples
--------

[](#examples)

For see complete example, please go to [examples](https://github.com/aminyazdanpanah/handling-file-uploads/blob/master/examples).

Contributing
------------

[](#contributing)

I'd love your help in improving, correcting, adding to the specification. Please [file an issue](https://github.com/aminyazdanpanah/handling-file-uploads/issues)or [submit a pull request](https://github.com/aminyazdanpanah/handling-file-uploads/pulls).

Please see [Contributing File](https://github.com/aminyazdanpanah/handling-file-uploads/blob/master/CONTRIBUTING.md) for more information.

Security
--------

[](#security)

If you discover a security vulnerability within this package, please send an e-mail to Amin Yazdanpanah via: contact \[AT\] aminyazdanpanah • com.

Credits
-------

[](#credits)

- [Amin Yazdanpanah](http://www.aminyazdanpanah.com/?u=github.com/aminyazdanpanah/handling-file-uploads)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/aminyazdanpanah/handling-file-uploads/blob/master/LICENSE) for more information.

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity13

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 91.7% 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 ~36 days

Recently: every ~45 days

Total

6

Last Release

2459d ago

PHP version history (2 changes)v1.0.0PHP ^7.1.0

v1.1.14PHP ^7.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/a73aaac753c327bdc55306a38bb829db7a8435ef17a742d94f2917bbf1bfc12e?d=identicon)[aminyazdanpanah](/maintainers/aminyazdanpanah)

---

Top Contributors

[![aminyazdanpanah](https://avatars.githubusercontent.com/u/3193929?v=4)](https://github.com/aminyazdanpanah "aminyazdanpanah (33 commits)")[![renovate-bot](https://avatars.githubusercontent.com/u/25180681?v=4)](https://github.com/renovate-bot "renovate-bot (3 commits)")

---

Tags

filefile-sizefilesimage-uploadimage-uploaderlaravellaravel-5-packagepackagistphpphp-libraryphp7savesave-filesuploaduploadervalidatevalidationvalidatorvideo-uploadvideo-uploaderphpvalidatorimagearchiveaudiovideofileuploadsavefilenamemove to

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/aminyazdanpanah-handling-file-uploads/health.svg)

```
[![Health](https://phpackages.com/badges/aminyazdanpanah-handling-file-uploads/health.svg)](https://phpackages.com/packages/aminyazdanpanah-handling-file-uploads)
```

###  Alternatives

[kartik-v/bootstrap-fileinput

An enhanced HTML 5 file input for Bootstrap 5.x, 4.x, and 3.x with features for file preview for many file types, multiple selection, ajax uploads, and more.

5.4k7.9M13](/packages/kartik-v-bootstrap-fileinput)[fof/upload

The file upload extension for the Flarum forum with insane intelligence.

188171.7k15](/packages/fof-upload)[transloadit/php-sdk

Transloadit SDK

63393.6k2](/packages/transloadit-php-sdk)[blueimp/jquery-file-upload

File Upload widget for jQuery.

141.5M18](/packages/blueimp-jquery-file-upload)[itskodinger/midia

Simple Media manager for your Laravel project

1415.8k](/packages/itskodinger-midia)

PHPackages © 2026

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