File uploads with validation and storage strategies

Related tags

Miscellaneous Upload
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
This PHP class uploads files and manipulates images very easily

This PHP class uploads files and manipulates images very easily. It is in fact as much as an image processing class than it is an upload class. Compatible with PHP4, 5 and 7. Supports processing of local files, uploaded files, files sent through XMLHttpRequest.

Colin Verot 795 Dec 21, 2022
PHP library providing retry functionality with multiple backoff strategies and jitter support

PHP Backoff Easily wrap your code with retry functionality. This library provides: 4 backoff strategies (plus the ability to use your own) Optional ji

Signature Tech Studio 145 Dec 21, 2022
Tiny PHP library providing retry functionality with multiple backoff strategies and jitter support

JBZoo / Retry 4 retry strategies (plus the ability to use your own) Optional jitter / randomness to spread out retries and minimize collisions Wait ti

JBZoo Toolbox 6 Dec 19, 2022
High-performance, low-memory-footprint, single-file embedded database for key/value storage

LDBA - a fast, pure PHP, key-value database. Information LDBA is a high-performance, low-memory-footprint, single-file embedded database for key/value

Simplito 12 Nov 13, 2022
File Storage Api

flux-file-storage-api File Storage Api Installation Native Download RUN (mkdir -p /%path%/libs/flux-file-storage-api && cd /%path%/libs/flux-file-stor

null 1 Dec 12, 2022
This component simplifies file validation and uploading.

This component simplifies file validation and uploading.

Brandon Savage 1.7k Dec 27, 2022
A simple mailable trait and interface to export mails to a storage disk once being sent.

Laravel Mail Export This package can export any mail sent with Laravel's Mailable class to any desired filesystem disk and path as a .eml file. This c

Pod Point 80 Nov 6, 2022
Greyhole uses Samba to create a storage pool of all your available hard drives, and allows you to create redundant copies of the files you store.

Greyhole Greyhole is an application that uses Samba to create a storage pool of all your available hard drives (whatever their size, however they're c

Guillaume Boudreau 245 Dec 18, 2022
Laravel & Google Drive Storage - Demo project with Laravel 6.x and earlier

Laravel & Google Drive Storage Demo project with Laravel 8.X Look at the commit history to see each of the steps I have taken to set this up. Set up t

null 23 Oct 3, 2022
Upload attachments to content storage platform like Aliyun OSS, Tencent COS

Overview Yun storage provides a layer that mediates between a user or configured storage frontend and one or several storage backends. Note: jichangfe

Changfeng Ji 2 Oct 13, 2021
A Qiniu Storage filesystem for Laravel

Laravel filesystem Qiniu Qiniu storage for Laravel based on overtrue/flysystem-qiniu. Requirement PHP >= 5.5.9 Installation $ composer require "overtr

安正超 463 Dec 6, 2022
This Repo is a storage of Postman collections for Magento

Magento Postman repository This Repository is a storage of Postman collections for Magento. If you have what to share, you are welcome to contribute a

Lyzun Oleksandr 14 May 17, 2022
Google Cloud Storage for PHP

Google Cloud Storage for PHP Idiomatic PHP client for Cloud Storage. API documentation NOTE: This repository is part of Google Cloud PHP. Any support

Google APIs 281 Nov 10, 2022
Microsoft Azure Storage Library for PHP

Microsoft Azure Storage PHP Client Libraries This project will be in Community Support and Azure Storage team commits to validate and release every qu

Microsoft Azure 201 Nov 30, 2022
PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule for validation Japanese string only full-width or only half-width.

Japanese String Helpers PHP Japanese string helper functions for converting Japanese strings from full-width to half-width and reverse. Laravel Rule f

Deha 54 Mar 22, 2022
The main scope of this extension is to help phpstan to detect the type of object after the Assert\Assertion validation.

PHPStan beberlei/assert extension PHPStan beberlei/assert Description The main scope of this extension is to help phpstan to detect the type of object

PHPStan 33 Jan 2, 2023
The last validation library you will ever need!

Mighty The last validation library you will ever need! Table of Contents Installation About Mighty Quickstart Mighty Validation Expression Language Ex

Marwan Al-Soltany 55 Jan 3, 2023
PHP Standalone Validation Library

Rakit Validation - PHP Standalone Validation Library PHP Standalone library for validating data. Inspired by Illuminate\Validation Laravel. Features A

Rakit Lab 727 Dec 30, 2022
Actions: controller + auth + validation in one class

Actions: controller + auth + validation in one class This package provides only one class: an Action class that extends the FormRequest class we all k

edatta 2 Dec 15, 2022