• Stars
    star
    459
  • Rank 95,377 (Top 2 %)
  • Language
    PHP
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHP FileUpload library that supports chunked uploads

FileUpload

Build Status

PHP FileUpload library that supports chunked uploads. Adopted from the procedural script included with jQuery-File-Upload, designed to work with that JavaScript plugin, with normal forms, and to be embeddable into any application/architecture.

Installing

This package is available via Composer:

{
  "require": {
    "gargron/fileupload": "~1.4.0"
  }
}

Requirements

  • Ensure that the PHP extension "php_fileinfo" is enabled;

  • Your php.ini must have the next directive:

file_uploads = On

Status

The unit test suite covers simple uploads and the library "works on my machine", as it were. You are welcome to contribute.

You can grep the source code for TODO to find things you could help finishing.

Usage

// Simple validation (max file size 2MB and only two allowed mime types)
$validator = new FileUpload\Validator\Simple('2M', ['image/png', 'image/jpg']);

// Simple path resolver, where uploads will be put
$pathresolver = new FileUpload\PathResolver\Simple('/my/uploads/dir');

// The machine's filesystem
$filesystem = new FileUpload\FileSystem\Simple();

// FileUploader itself
$fileupload = new FileUpload\FileUpload($_FILES['files'], $_SERVER);

// Adding it all together. Note that you can use multiple validators or none at all
$fileupload->setPathResolver($pathresolver);
$fileupload->setFileSystem($filesystem);
$fileupload->addValidator($validator);

// Doing the deed
list($files, $headers) = $fileupload->processAll();

// Outputting it, for example like this
foreach($headers as $header => $value) {
    header($header . ': ' . $value);
}

echo json_encode(['files' => $files]);

foreach($files as $file){
    //Remeber to check if the upload was completed
    if ($file->completed) {
        echo $file->getRealPath();
        
        // Call any method on an SplFileInfo instance
        var_dump($file->isFile());
    }
}

Alternative usage via factory

$factory = new FileUploadFactory(
    new PathResolver\Simple('/my/uploads/dir'), 
    new FileSystem\Simple(), 
    [
        new FileUpload\Validator\MimeTypeValidator(['image/png', 'image/jpg']),
        new FileUpload\Validator\SizeValidator('3M', '1M') 
        // etc
    ]
);

$instance = $factory->create($_FILES['files'], $_SERVER);

Validators

There are currently 4 validators shipped with FileUpload:

  • Simple
// Simple validation (max file size 2MB and only two allowed mime types)
$validator = new FileUpload\Validator\Simple('2M', ['image/png', 'image/jpg']);
  • MimeTypeValidator
$mimeTypeValidator = new FileUpload\Validator\MimeTypeValidator(['image/png', 'image/jpg']);
  • SizeValidator
// The 1st parameter is the maximum size while the 2nd is the minimum size
$sizeValidator = new FileUpload\Validator\SizeValidator('3M', '1M');
  • DimensionValidator
$config = [
     'width' => 400,
     'height' => 500
]; 
// Can also contain 'min_width', 'max_width', 'min_height' and 'max_height'

$dimensionValidator = new FileUpload\Validator\DimensionValidator($config);

Remember to register new validator(s) by $fileuploadInstance->addValidator($validator);

If you want you can use the common human readable format for filesizes like '1M', '1G', just pass the string as the first argument.

$validator = new FileUpload\Validator\Simple('10M', ['image/png', 'image/jpg']);

Here is a listing of the possible values (B => B; KB => K; MB => M; GB => G). These values are binary convention so basing on 1024.

FileNameGenerator

With the FileNameGenerator you have the possibility to change the filename the uploaded files will be saved as.

$fileupload = new FileUpload\FileUpload($_FILES['files'], $_SERVER);
$filenamegenerator = new FileUpload\FileNameGenerator\Simple();
$fileupload->setFileNameGenerator($filenamegenerator);
  • Custom
$customGenerator = new FileUpload\FileNameGenerator\Custom($provider);
//$provider can be a string (in which case it is returned as is)
//It can also be a callable or a closure which receives arguments in the other of $source_name, $type, $tmp_name, $index, $content_range, FileUpload $upload
  • MD5
$md5Generator = new FileUpload\FileNameGenerator\MD5($allowOverride);
//$allowOverride should be a boolean. A true value would overwrite the file if it exists while a false value would not allow the file to be uploaded since it already exists.
  • Random
$randomGenerator = new FileUpload\FileNameGenerator\Random($length);
//Where $length is the maximum length of the generator random name
  • Simple
$simpleGenerator = new FileUpload\FileNameGenerator\Simple();
//Saves a file by it's original name
  • Slug
$slugGenerator = new FileUpload\FileNameGenerator\Slug();
//This generator slugifies the name of the uploaded file(s)

Remember to register new validator(s) by $fileuploadInstance->setFileNameGenerator($generator);

Every call to setFileNameGenerator overrides the currently set $generator

Callbacks

Currently implemented events:

  • completed
$fileupload->addCallback('completed', function(FileUpload\File $file) {
    // Whoosh!
});
  • beforeValidation
$fileUploader->addCallback('beforeValidation', function (FileUpload\File $file) {
    // About to validate the upload;
});
  • afterValidation
$fileUploader->addCallback('afterValidation', function (FileUpload\File $file) {
    // Yay, we got only valid uploads
});

Extending

The reason why the path resolver, the validators and the file system are abstracted, is so you can write your own, fitting your own needs (and also, for unit testing). The library is shipped with a bunch of "simple" implementations which fit the basic needs. You could write a file system implementation that works with Amazon S3, for example.

License

Licensed under the MIT license, see LICENSE file.

More Repositories

1

blurhash

Encode an image as a small string that can be saved in the database, returned in API responses, and displayed as a blurred preview before the real image loads
C
288
star
2

cobalt

An open-source self-hosted YouTube alternative. Subscribe to other users on other servers using ActivityPub. Reduced bandwidth costs for server owners via WebTorrent.
Ruby
93
star
3

xmpp-web

A modern XMPP client for the web
JavaScript
66
star
4

zoomie

A JavaScript zoom-on-hover tool for images, like a magnifying glass. Really cool.
JavaScript
43
star
5

boost-bot

Mastodon bot that boosts all local toots with a chosen hashtag.
JavaScript
24
star
6

tusky-api

Node.js server that proxies Mastodon notifications to an app's push notifications through Firebase Cloud Messaging
JavaScript
20
star
7

blurhash.js

Mirror
TypeScript
14
star
8

baron

Baron is a WebRTC-based IM for the browser
JavaScript
12
star
9

pubsubhubbub

A mountable PubSubHubbub server for Rails
Ruby
9
star
10

Snowfall

HTML5-canvas based snowfall JavaScript
JavaScript
9
star
11

Paginator

Minimal PHP paginator class. Generates pagination navigation based on total items number and offset.
PHP
8
star
12

book-toot-bot

A Ruby script that will post a book to a Mastodon account.
Ruby
7
star
13

passwordCheck.js

Password strength evaluator
JavaScript
5
star
14

Capture

Open-source quick screen grabbing tool in Python
Python
4
star
15

ElasticEmail-PHP

PHP class for ElasticEmail.com
PHP
3
star
16

generic-ban

A generic PHP ban class. Supports IP bans, alt account bans, and expiring bans. Uses redis.
PHP
3
star
17

mastodon-java-api-example

Example Android app that uses Mastodon API via OAuth2
Java
3
star
18

zeon

Minimalist federated message board in Ruby
Ruby
3
star
19

colorless-chat

Web group chat
JavaScript
2
star
20

delight

Desktop client for Matrix
JavaScript
2
star
21

colorless-old

theColorless.net archive codebase
PHP
2
star
22

SaDOS

A guiding tutorial console in JavaScript
JavaScript
2
star
23

twittersphere

A thing that fetches user connections from Twitter and exports them to a GDF (directed graph file) that can be used e.g. in Gephi
Ruby
1
star
24

colorless-hotkeys

Navigation hotkeys for theColorless.net
JavaScript
1
star
25

doujinshi_txt

JavaScript
1
star
26

Colorchat

Ruby and EventMachine-based webchat application supporting WebSockets and a Comet fallback
Ruby
1
star