File uploads with validation and storage strategies

Overview

Upload

Build Status Latest Version Total Downloads

This component simplifies file validation and uploading.

Usage

Assume a file is uploaded with this HTML form:

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="foo" value=""/>
    <input type="submit" value="Upload File"/>
</form>

When the HTML form is submitted, the server-side PHP code can validate and upload the file like this:

<?php
$storage = new \Upload\Storage\FileSystem('/path/to/directory');
$file = new \Upload\File('foo', $storage);

// Optionally you can rename the file on upload
$new_filename = uniqid();
$file->setName($new_filename);

// Validate file upload
// MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
$file->addValidations(array(
    // Ensure file is of type "image/png"
    new \Upload\Validation\Mimetype('image/png'),

    //You can also add multi mimetype validation
    //new \Upload\Validation\Mimetype(array('image/png', 'image/gif'))

    // Ensure file is no larger than 5M (use "B", "K", M", or "G")
    new \Upload\Validation\Size('5M')
));

// Access data about the file that has been uploaded
$data = array(
    'name'       => $file->getNameWithExtension(),
    'extension'  => $file->getExtension(),
    'mime'       => $file->getMimetype(),
    'size'       => $file->getSize(),
    'md5'        => $file->getMd5(),
    'dimensions' => $file->getDimensions()
);

// Try to upload file
try {
    // Success!
    $file->upload();
} catch (\Exception $e) {
    // Fail!
    $errors = $file->getErrors();
}

How to Install

Install composer in your project:

curl -s https://getcomposer.org/installer | php

Require the package with composer:

php composer.phar require codeguy/upload

Author

Josh Lockhart

License

MIT Public License

Comments
  • Cannot use composer to add the project

    Cannot use composer to add the project

    I tried to get the project using composer and have this error:

    Updating dependencies (including require-dev)

    • Installing codeguy/upload (1.3.1) Downloading: connection... Could not fetch http://nodeload.github.com/codeguy/Upload/zip/1.3.1, enter your GitHub > credentials to access private repos The credentials will be swapped for an OAuth token stored in C:/Documents and >Settings/xxxxx/Application Data/Composer/config.json, your password will not be stored To revoke access to this token you can visit https://github.com/settings/applications Username: ...

    And after I add my GitHub credentials I get this error:

    [Composer\Downloader\TransportException] The "https://api.github.com/authorizations" file could not be downloaded: U nable to find the wrapper "https" - did you forget to enable it when you co nfigured PHP? failed to open stream: Invalid argument

    Any idea why?

    I tried this from 2 different locations and I have the same issue... Importing other repositories with composer works perfectly so... I really don't get it why for your repo it give me this error.

    Thanks

    opened by cristianciofu 17
  • How to use with an array of files

    How to use with an array of files

    Hello to All contributors i want to use the library to upload multiple files in the same request...

    Any HOW TO would be a great help.

    Actually using it on a client project & it works well....

    opened by PapePathe 11
  • Allowing Multiple FileTypes

    Allowing Multiple FileTypes

    Following along with the README.md I noticed that I could not seem to add additional checks for the Mime types.

      // Validate file upload
      // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml
      $file->addValidations(array(
          // Ensure file is of type "image/png", "image/jpeg", or "image/gif"
          new \Upload\Validation\Mimetype('image/png'),
          new \Upload\Validation\Mimetype('image/jpeg'),
          new \Upload\Validation\Mimetype('image/gif'),
    
          // Ensure file is no larger than 5M (use "B", "K", M", or "G")
          new \Upload\Validation\Size('5M')
      ));
    

    If I commented out any 2 types and then tried to upload an image of that type it worked, but if I have all 3 enabled, then it errors saying it's not the correct type.

    opened by jeffdupont 10
  • setName usage in documentation appears to be wrong

    setName usage in documentation appears to be wrong

    Trying to use the class as demonstrated in the docs doesn't work.

    It's trying to access setName on the main file class. No such method.

    In order to access the setName method I have to access the fileInfo class in the objects collection from outside the File class as follows:

    $files = &$file->getIterator(); foreach($files as &$f) { $f->setName( uniqid() ); }

    opened by gabrielalack 8
  • File upload Empty

    File upload Empty

    Good Day, i try to use this library on a simple slim framework project,

    then using all the basic code and try to upload file it works and no error message appears, but when i check the upload folder it´s empty, also i attach the dump vars.

    there is any that i miss?... many thanks

    screen shot 2014-09-27 at 9 39 25 am

    bug 
    opened by carlos-andres 5
  • Allow a new name to be passed to upload()

    Allow a new name to be passed to upload()

    Give an image a new name, which will respect the extension provided in the name, or if none is passed it will use the original extension.

    I'd REALLY like to have set up a test for this with vfsStream but that would require a shitload of rewriting. Is this something you could look into going forwards? Otherwise I'd need to actually make a new file, which isn't cool and permission issues could cause tests to fail even though the code is fine.

    opened by philsturgeon 5
  • Class finfo not found

    Class finfo not found

    Hi, I'm using Laravel 4.2 with your library installed by composer. Suddenly yesterday I started to get this error: exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'finfo' not found' in /home/tmyndrzy/public_html/vendor/codeguy/upload/src/Upload/File.php:203

    There have been no environment changes that I am aware of, I'm using PHP 5.4.

    opened by donwildman 3
  • How to access data about the file after latest update?

    How to access data about the file after latest update?

    Hello!

    We are using your Upload project in our application, but recently you have updated your code and it is not B/C :( Now all methods of getting file info like $file->getName() are not working. How to access data about the file after latest update?

    And hot to set new file name before upload? :) Thanks!

    bug 
    opened by b2z 3
  • How to get uploaded file path

    How to get uploaded file path

    I had found the File class has not a method to get uploaded file path and upload can not return the path.

    I want to extent this or you have the better idea?

    opened by hfcorriez 3
  • Max POST size

    Max POST size

    Hey,

    I just read over the code quickly so I may have missed this, but did you implement an error for if the file exceeds the maximum POST size? That is, when a POST exceeds the maximum size, the returned POST array is empty (Which can cause a lot of headaches for those who are unaware of this behaviour).

    If you have, then ignore this ;)

    opened by telephone 3
  • It was uploading files now has stopped

    It was uploading files now has stopped

    Package was working fine but now it just keeps throwing an error and not uploading files.

    Run a var dump on the error and says;

    object(Upload\Exception\UploadException)#131 plus whole load more.

    This is my code;

    <?php
    
    namespace App\Controllers;
    
    use App\Controllers\Controller;
    use Upload\Storage\FileSystem;
    use Upload\File;
    use Upload\Validation\MimeType;
    use Upload\Validation\Size;
    
    //import validator
    use Respect\Validation\Validator as v;
    
    class ImageController extends Controller
    {
    
        
    	public function getImageUpload($request,$response){
    		return $this->view->render($response,'admin-upload.twig');
    	}
    
        public function postImageUpload($request,$response){
            $dir = USER_ROOT;
            $storage = new \Upload\Storage\FileSystem($_SERVER['DOCUMENT_ROOT'] . "/img");
            $file = new \Upload\File('upload',$storage);
    
          //  $new_filename = uniqid();
           // $file->setName($new_filename);
    
           
            $file->addValidations(array(
                new \Upload\Validation\Mimetype(array('image/png','image/gif','image/jpg','image/jpeg')),
    
                new \Upload\Validation\Size('20M')
            ));
            
    
            // Access data about the file that has been uploaded
            $data = array(
                'name'       => $file->getNameWithExtension(),
                'extension'  => $file->getExtension(),
                'mime'       => $file->getMimetype(),
                'size'       => $file->getSize(),
                'md5'        => $file->getMd5(),
                'dimensions' => $file->getDimensions()
            );
            // Try to upload file
            try {
                
                if ($file->upload()) {
                    $this->flash->addMessage('success','Image uploaded');
                    $this->flash->addMessage('info','Make sure to add the same name i.e. image.jpg as a string in other form submission');
                    return $response->withRedirect($this->router->pathFor('admin.update')); 
                }
    	
            } catch (\Exception $e) {
                // Fail!
                
                $errors = $file->getErrors();
                var_dump($e);
                $this->flash->addMessage('error',$errors);
                return $response->withRedirect($this->router->pathFor('admin.update'));
            }
        }
    }
    
    opened by mayurpande 2
  • Multiple input file with array in name attribut

    Multiple input file with array in name attribut

    Hello,

    If you have this form:

    <form method="post" action="#" enctype="multipart/form-data">
        <input type="file" class="form-control" name="photo_name[0]">
        <input type="file" class="form-control" name="photo_name[1]">
    </form>
    

    You can't use this component:

    $file = new \Upload\File('photo_name', $this->localStorage);
    

    SplFileInfo::__construct() expects parameter 1 to be a valid path, array given

    OR

    $file = new \Upload\File('photo_name[0]', $this->localStorage);
    

    Cannot find uploaded file identified by key: photo_name[0]

    var_dump($_FILES);
    

    array (size=1) 'photo_name' => array (size=5) 'name' => array (size=1) 0 => string '123.jpeg' (length=43) 'type' => array (size=1) 0 => string 'image/jpeg' (length=10) 'tmp_name' => array (size=1) 0 => string 'C:\wamp64\tmp\phpDF44.tmp' (length=25) 'error' => array (size=1) 0 => int 0 'size' => array (size=1) 0 => int 1443745

    I don't see anything about this behaviour.

    Temporarily i hack \Upload\File constructor like this:

    public function __construct($key, \Upload\Storage\Base $storage, ?int $index = null)
        {
            if (! isset($_FILES[$key])) {
                throw new \InvalidArgumentException("Cannot find uploaded file identified by key: $key");
            }
            $this->storage = $storage;
            $this->validations = array();
            $this->errors = array();
            if (is_null($index)) {
                $this->originalName = $_FILES[$key]['name'];
                $this->errorCode = $_FILES[$key]['error'];
                parent::__construct($_FILES[$key]['tmp_name']);
            } else {
                $this->originalName = $_FILES[$key]['name'][$index];
                $this->errorCode = $_FILES[$key]['error'][$index];
                parent::__construct($_FILES[$key]['tmp_name'][$index]);
            }
        }
    

    It seems to work, i hope you will fix it if you can for next release.

    Best regards,

    opened by fdirson-OpenGateway 0
  • Any plans for a new release?

    Any plans for a new release?

    I am currently using this package in a project and I had to specify dev-master in my composer file because there are some classes that have been added that are not part of the latest release. I am not comfortable specifying dev-master in my composer file and would really love if a new stable release could be created ASAP.

    Thanks for this wonderful package.

    opened by rotexdegba 4
  • How to keep uploaded filename and write filename to db

    How to keep uploaded filename and write filename to db

    Hi I am trying to use this on a project and it works fine with uploading the files with the unique id - but I was wondering how I can get it to use the uploaded files name and write it to the database.

    This is my code (controller, text-model and imagemodel)

    Text controller:

    public function update($slug,Request $request, Response $response, Router $router, Twig $view, Text $text, Billede $billede)
        {
            
            $update = $text->where('id', $slug)->update([
                'overskrift' => $request->getParam('overskrift'),
                'tekst' => $request->getParam('tekst'),
                'link' => $request->getParam('link'),
                'billede_id' => $billede->id,
                ]);       
                $var = 'billede';
                $billede = $billede->firstOrCreate([
            //            'alt' => $request->getParam('alt'),
                     
                    'billedenavn' =>  $billede->upload($var),
                ]);
                 
                $billede->text()->save($update);
            print_r($new_filename);
    }
    

    My textmodel

    <?php
    
    namespace Cart\Models;
    
    use Cart\Models\User;
    use Cart\Models\Admin;
    use Cart\Models\Text;
    use Cart\Models\Billede;
    use Upload\Storage\FileSystem;
    use Upload\File;
    use Upload\Validation\Mimetype;
    use Upload\Validation\Size;
    use Illuminate\Database\Eloquent\Model;
    
    class Text extends Model
    {
        protected $table = 'webshoptekst';
        protected $foreignKey = 'billede_id';
    
        protected $fillable = [
            'overskrift',
            'tekst',
            'billede_id',
            'filer',
            'linktekst',
            'navigationId',
            'navn',
          ];
    
        public static function txt() {
    
          return Text::get()->all();
        }
        
        public function Pages()
        {
            return $this->hasOne(Text::class, 'id', 'navn');
        }
      }
       
    

    My image model (billedemodel)

    <?php
    
    namespace Cart\Models;
    
    use Cart\Models\Billede;
    use Cart\Models\Text;
    use Upload\Storage\FileSystem;
    use Upload\File;
    use Upload\Validation\Mimetype;
    use Upload\Validation\Size;
    use Illuminate\Database\Eloquent\Model;
    
    class Billede extends Model
    {
        protected $table = 'webshopbilleder';
    
    
        protected $fillable = [
            'billedenavn',
          ];
    
          public function text(){
            return $this->hasOne(Text::class);
        }  
    
        public function upload() {
        $storage = new \Upload\Storage\FileSystem('../public/uploads');
        $file = new \Upload\File('billede', $storage);
    
        // Optionally you can rename the file on upload
        $new_filename = uniqid('GK' . '-');
        $file->setName($new_filename);
    
        // Validate file upload
        // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml
        $file->addValidations(array(
            // Ensure file is of type "image/png"
            // new \Upload\Validation\Mimetype('image/png'),
    
            //You can also add multi mimetype validation
            new \Upload\Validation\Mimetype(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pdf')),
    
            // Ensure file is no larger than 5M (use "B", "K", M", or "G")
            new \Upload\Validation\Size('5M')
        ));
    
        // Access data about the file that has been uploaded
        $data = array(
            'name'       => $file->getNameWithExtension(),
            'extension'  => $file->getExtension(),
            'mime'       => $file->getMimetype(),
            'size'       => $file->getSize(),
            'md5'        => $file->getMd5(),
            'dimensions' => $file->getDimensions()
        );
    
        // Try to upload file
        try {
            // Success!
            $file->upload();
        } catch (\Exception $e) {
            // Fail!
            $errors = $file->getErrors();
        }        
      }
    
      public $timestamps = false;
    }
    
    

    It uploads the files as it should with uniq-id but I can't get it to write the name to the database.

    Can anyone help - please

    opened by Budolfsen 3
  • Html Canvas & Javascript FileReader

    Html Canvas & Javascript FileReader

    Hi, I have somewhat modern implementation of the file upload. It combines "croppie", a tool that allows a user to move and crop the image, and Javascript FileReader feature. Result is POSTed to the PHP API as an encoded string:

    data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJ4AA...

    Unfortunately the Upload library doesn't recognise this format.

    Cannot find uploaded file identified by key: image
    codeguy/upload/src/Upload/File.php
    
    

    Is there a way around this?

    opened by mategvo 1
Releases(1.3.2)
  • 1.3.2(Jul 7, 2013)

    • NEW: Add getDimensions method to return uploaded image height and width
    • NEW: Add getMd5 method to return md5 hash of uploaded file
    • UPDATE: Let getExtension always return lowercase file extension
    Source code(tar.gz)
    Source code(zip)
Owner
Brandon Savage
Brandon Savage
Lightweight and feature-rich PHP validation and filtering library. Support scene grouping, pre-filtering, array checking, custom validators, custom messages. 轻量且功能丰富的PHP验证、过滤库。支持场景分组,前置过滤,数组检查,自定义验证器,自定义消息。

PHP Validate 一个简洁小巧且功能完善的php验证、过滤库。 简单方便,支持添加自定义验证器 支持前置验证检查, 自定义如何判断非空 支持将规则按场景进行分组设置。或者部分验证 支持在进行验证前对值使用过滤器进行净化过滤内置过滤器 支持在进行验证前置处理和后置处理独立验证处理 支持自定义每

Inhere 246 Jan 5, 2023
Abstracts HTTP request input handling, providing an easy interface for data hydration and validation

Linio Input Linio Input is yet another component of the Linio Framework. It aims to abstract HTTP request input handling, allowing a seamless integrat

Linio 41 Dec 12, 2021
Light and extendable schema validation library

Light PHP validation library For everyone who uses MongoDB or other NoSQL solution and cares about what client sends to his/her database and looking f

Alexander Serkin 43 Sep 28, 2022
Validation rules for Money and Currency

money-validation-laravel Validation rules for Money and Currency Installation composer require brokeyourbike/money-validation-laravel Usage Package us

Ivan Stasiuk 1 Oct 25, 2021
Valitron is a simple, elegant, stand-alone validation library with NO dependencies

Valitron: Easy Validation That Doesn't Suck Valitron is a simple, minimal and elegant stand-alone validation library with NO dependencies. Valitron us

Vance Lucas 1.5k Dec 30, 2022
[READ-ONLY] Validation library from CakePHP. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Validation Library The validation library in CakePHP provides features to build validators that can validate arbitrary arrays of data with eas

CakePHP 39 Oct 11, 2022
One Line Validation, For CodeIgniter 4

One Line Validation (OLV) is a package made for CodeIgniter 4 to provide a fast and single line validation experience ideal for CDN and/or API services consuming the Validation System from CodeIgniter 4.

AJ Meireles 2 Sep 21, 2021
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
高性能的验证器组件(Validation),适用于 Hyperf 或 Laravel 框架,可获得数百倍的性能提升

验证器 简介 兼容 Hyperf/Laravel Validation 规则 部分场景可获得约 500 倍性能提升 验证器可多次复用不同数据,无状态设计 规则可全局复用 智能合并验证规则 安装 环境要求 PHP >= 8.0 mbstring 扩展 ctype 扩展 安装命令 composer re

KK集团 80 Dec 9, 2022
Extension for the Laravel validation class

Intervention Validation Intervention Validation is an extension library for Laravel's own validation system. The package adds rules to validate data l

null 370 Dec 30, 2022
Extra validation rules for dealing with images in Laravel 5.

Image-Validator Extra validation rules for dealing with images in Laravel 5. NOTE: As of Laravel version 5.2, there are now built-in validation rules

Colin Viebrock 223 Jun 16, 2022
laminas-password-validator provides a validator for character-set based input validation.

laminas-password-validator laminas-password-validator provides a validator for character-set based input validation. Installation composer require pra

null 1 Mar 8, 2022
Laravel Validation Service

Laravel Validation Service Installation Add "prettus/laravel-repository": "1.1.*" to composer.json "prettus/laravel-validation": "1.1.*" Create a vali

Anderson Andrade 398 Nov 25, 2022
An extensible validation library for your data with sane defaults.

Hird Hirds, also known as housecarls, was a gathering of hirdmen, who functioned as the king's personal guards during the viking age and the early mid

Asko Nõmm 13 Apr 23, 2022
FyreValidation is a free, open-source validation library for PHP.

FyreValidation FyreValidation is a free, validation library for PHP. Table Of Contents Installation Validators Rules Error Messages Installation Using

Elusive 0 Jan 15, 2022
🔒 Laravel validation rule that checks if a password has been exposed in a data breach.

?? Laravel Password Exposed Validation Rule This package provides a Laravel validation rule that checks if a password has been exposed in a data breac

Jordan Hall 85 Apr 26, 2022
Validate and sanitize arrays and objects.

Aura.Filter This package provides tools to validate and sanitize objects and arrays. Foreword Installation This library requires PHP 5.4 or later; we

Aura for PHP 153 Jan 2, 2023
PHP library to validate and convert ISBNs and EANs

biblys/isbn biblys/isbn can be used to: validate a string against the ISBN-10, ISBN-13 and EAN-13 formats convert an ISBN to ISBN-10, ISBN-13, EAN-13

Biblys 48 Apr 10, 2022
This package provides tools to validate and sanitize objects and arrays.

Aura.Filter This package provides tools to validate and sanitize objects and arrays. Foreword Installation This library requires PHP 7.2 or later; we

Aura for PHP 153 Jan 2, 2023