This component simplifies file validation and uploading.

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:

$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(); }">

$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
Simplifies GST calculation and operations

Simplifies GST calculation and operations Installation You can install the package via composer: composer require gaurangsharma/gst-calculator Usage u

Gaurang Sharma 1 Oct 21, 2021
A multi-purpose web-shell that simplifies running shell commands on webserver

This webshell can be used for multi-purposed especially most if you want to manage your web server but you are in an emergency , so why not use a webshell:)

urchinsec 5 Oct 13, 2022
More options when uploading files such as name changes, resizing or compression through TinyPNG.

Kirby Upload Extended More options when uploading files like name changes, resizing via Kirby or compression and optional resizing via TinyPNG. Thanks

Oli 24 Nov 12, 2022
Laravel-Crowdin Integration - Automate translations uploading/downloading

Laravel-Crowdin Integration Automate uploading/downloading translations Installation Install the package via composer: composer require georgii-web/la

Joris van Willigen 0 May 25, 2022
File uploads with validation and storage strategies

Upload This component simplifies file validation and uploading. Usage Assume a file is uploaded with this HTML form: <form method="POST" enctype="mult

Brandon Savage 1.7k Dec 27, 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
Magento 2 Megamenu extension is an indispensable component, and plays the role of website navigation to help customers easily categorize and find information

Mageno 2 Mega Menu (Magicmenu) helps you create neat and smart navigation menus to display the main categories on your website.

https://magepow.com 35 Dec 1, 2022
This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized objects in DynamoDB 🚀.

DynamoDB Storable This component, based on the Symfony serializer and async-aws, is a human-readable and quick abstraction to easily store serialized

Matthieu W. 2 Jun 19, 2022
Powerful and flexible component for building site breadcrumbs.

Phalcon Breadcrumbs Phalcon Breadcrumbs is a powerful and flexible component for building site breadcrumbs. You can adapt it to your own needs or impr

Serghei Iakovlev 40 Nov 5, 2022
The ErrorHandler component provides tools to manage errors and ease debugging PHP code

ErrorHandler Component The ErrorHandler component provides tools to manage errors and ease debugging PHP code. Getting Started $ composer require symf

Symfony 2.2k Jan 3, 2023
An utility component for XML usage and best practices in PHP

An utility component for XML usage and best practices in PHP

Laminas Project 13 Nov 26, 2022
A PHP component to convert HTML into a plain text format

html2text html2text is a very simple script that uses DOM methods to convert HTML into a format similar to what would be rendered by a browser - perfe

Jevon Wright 423 Dec 29, 2022
This component provides a collection of functions/classes using the symfony/intl package when the Intl extension is not installed.

Symfony Polyfill / Intl: ICU This package provides fallback implementations when the Intl extension is not installed. It is limited to the "en" locale

Symfony 2.4k Jan 6, 2023
Debug - The Debug component provides tools to ease debugging PHP code.

Debug Component CAUTION: this component is deprecated since Symfony 4.4. Instead, use the ErrorHandler component. The Debug component provides tools t

Symfony 7.3k Jan 8, 2023
The Cache component provides an extended PSR-6 implementation for adding cache to your applications.

Symfony PSR-6 implementation for caching The Cache component provides an extended PSR-6 implementation for adding cache to your applications. It is de

Symfony 3.8k Jan 3, 2023