Coder Social home page Coder Social logo

upload's Introduction

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

upload's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

upload's Issues

more then 2 files

it seems to not like more then 2 files at a time.

how can we fix that?

error

finfo::file(G:\wamp\www\tmp\phpB5CC.tmp): failed to open stream: No such file or directory

i am getting this error when i use this in my app.

i am calling it in a class file. that allows my members to edit there avatar. but it gives this warning. i have it set up properly. it doesn't give me this error if i place it directly in a file without a oop style.

it uploads the avatar file. but i want to know how to get this error to stop showing.

Add a "validation only" mode

This library is great, and the new Flysystem integration looks awesome, but I think it would be worthwhile to make it possible to use Upload without any file system interaction. Something like this:

// Note the lack of $storage parameter
$file = new \Upload\File('foo');

// Add validation rules
$file->addValidations(array(
    //...
));

// Validate the uploaded file
try {
    // Success!
    $file->validate();

    // Manually move the file (ie. S3)

} catch (\Exception $e) {
    // Fail!
    $errors = $file->getErrors();
}

I don't think this would take much to do, and is maybe an appropriate change after the Flysystem integration has been completed.

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?

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 ;)

Runtime Exception on multiple file upload

Error
====
Fatal error: Uncaught exception 'RuntimeException' with message 'SplFileInfo::__construct() expects parameter 1 to be string, array given' in D:\xampp\htdocs\test\Uploading\libs\vendor\codeguy\upload\src\Upload\File.php:146 Stack trace: #0 D:\xampp\htdocs\test\Uploading\libs\vendor\codeguy\upload\src\Upload\File.php(146): SplFileInfo->__construct(Array) #1 D:\xampp\htdocs\test\Uploading\upload.php(19): Upload\File->__construct('uploadFile', Object(Upload\Storage\FileSystem)) #2 {main} thrown in D:\xampp\htdocs\test\Uploading\libs\vendor\codeguy\upload\src\Upload\File.php on line 146
Frontend Code
============
<form action="upload.php" method="post" enctype="multipart/form-data" name="form1" id="form1">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td><strong>multiple Files Upload </strong></td>
</tr>
<tr>
<td>Select file 
<input name="uploadFile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="uploadFile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td>Select file
<input name="uploadFile[]" type="file" id="ufile[]" size="50" /></td>
</tr>
<tr>
<td align="center"><input type="submit" name="Submit" value="Upload" /></td>
</tr>
</table>
</td>
</form>
Backend Code
============
$storage = new \Upload\Storage\FileSystem('uploads');
$file = new \Upload\File('uploadFile',$storage);

pathinfo UTF-8 bug

Hi
When I try to upload files with a name starting with UTF-8 characters (i.e. "Файл Test", first letters are cyrillic), after $file->upload() method $file->getName() prints string without UTF-8 characters (in my example just "Test", not "Файл Test").

As I understand this is caused by old bug with pathinfo() function. http://stackoverflow.com/questions/4451664/make-php-pathinfo-return-the-correct-filename-if-the-filename-is-utf-8

The issue seems to appear at line 156 of src/Upload/File.php
$this->name = pathinfo($this->originalName, PATHINFO_FILENAME);

As suggested in that SO thread, I put instead of this line following:
$this->name = pathinfo('1' . $this->originalName, PATHINFO_FILENAME);
$this->name = substr($this->name, 1);

and everything works fine. I could make pull request, but this solution seems a little bit hacky, and I don't know if this is good enough for your code conventions.

Thanks

Uploading files without an extension is not supported

On Linux and OS X, it's perfectly normal to have plain text files without any extension.

But if I upload a file named todo, the final name will be todo. (with a dot at the end).

This is due to the getNameWithExtension() method, which always appends a dot.

Spoofed file extension

Consider a situation where you are allowing users to upload files with mime image/png, image/jpeg, text/plain, ..etc.

Now, a user uploaded a file with spoofed extension, let's say an image image/png, this image when gets uploaded will be saved with filename.png, while getMimetype() will rather scan the content of the uploaded file and return text/plain.

Would it be better if we mapped the mime to extension instead of relying on pathinfo($desiredName, PATHINFO_EXTENSION) as it's not safe and can be faked?
Code: FileInfo

As an example:

function MimeToExtension($mime){
        $arr = array(
            'image/jpeg' => 'jpeg', 
            'image/png' => 'png',
            'application/msword' => 'doc',
            'application/pdf' => 'pdf'
        );
        return isset($arr[$mime])? $arr[$mime]: null;
    }

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

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....

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.

using Upload

Hi guys ,

Awesome stuff here ,

I was wondering , how would I use all these functions in one class ?

e.g File.php / Storage etc ..

Thanks Allot

The ability to get the current directory in the fileinfo object

Should be a simple tweak, i'll put in a PR later:

public function __construct($filePathname, $newName = null)
{
    $desiredName = is_null($newName) ? $filePathname : $newName;
    $this->name = pathinfo($desiredName, PATHINFO_FILENAME);
    $this->directory = pathinfo($desiredName, PATHINFO_DIRNAME);
    $this->extension = strtolower(pathinfo($desiredName, PATHINFO_EXTENSION));
    parent::__construct($filePathname);
}

/**
 * Get directory path of the current file
 *
 * @return string
 */
public function getDirectory()
{
    return $this->directory;
}

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

Cannot find uploaded file identified by key:

i have a code:

$arquivo = $app->request()->post('teste');
$local = ROOT."public" . DS . "media" . DS;
$storage = new \Upload\Storage\FileSystem($local);
$file = new \Upload\File($arquivo, $storage);

this return the message: Cannot find uploaded file identified by key:

Cannot use composer to add the project

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

Updating dependencies (including require-dev)

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

Add validation for image width/height

It might be worthwhile extending \Upload\File with \Upload\Image and implementing getHeight() and getWidth() methods rather than special case image detection in a validation class.

Image width / height validation

Title says it all :)

Proposed class:

<?php

namespace Upload\Validation;

use Upload\Exception;
use Upload\FileInfoInterface;
use Upload\ValidationInterface;

class ImageSize implements ValidationInterface
{
    function __construct($width, $height)
    {
        $this->width = $width;
        $this->height = $height;
    }

    public function validate(FileInfoInterface $info)
    {
        $dimensions = $info->getDimensions();
        $filename = $info->getNameWithExtension();
        if (!$dimensions) {
            throw new Exception(sprintf('%s: Could not detect image size.', $filename));
        }
        if ($dimensions['width'] != $this->width) {
            throw new Exception(
                sprintf(
                    '%s: Image width(%dpx) does not match required width(%dpx)',
                    $filename,
                    $dimensions['width'],
                    $this->width
                )
            );
        }
        if ($dimensions['height'] != $this->height) {
            throw new Exception(
                sprintf(
                    '%s: Image height(%dpx) does not match required height(%dpx)',
                    $filename,
                    $dimensions['height'],
                    $this->height
                )
            );
        }
    }
}

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.

set newname along with extension

the setName method only allows name .
a similar method will be helpful like setNameWithExtension .

suppose users are uploading php files with extension .php , but in the server i want remove that extension .

empty file submission

Hello,

First, thanks for your work !!
I've noted that sending empty file raise an error after creating the file and setting a new name if the submitted file is not setted

$file = new File($name, $storage);
$file->setName( $name ); [raise error if key ok but error code 4]

You raise an exception if a not existing key is submitted but you don't check the error 4 (empty path) when creating a new name.

Perhaps i'm not using correctly the API. Let me know.
I do my own check in the meantime.

With regards,
Rodney

Image dimensions

I appreciate image uploads are only one file type but would it be possible to return the dimensions of an uploaded image? Then access them in the $data array.

Having this would avoid multiple processing and be really useful.

Thanks, great package so far. Using with Laravel 4.

getNameWithExtension() method returning a dot

echo $file->getNameWithExtension();

This returns a '.' ( a dot)

So when we are uploading an empty post, in which we validate for an empty array we get a non empty array:

Array ( [name] => . [extension] => [mime] => [size] => )

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!

getMimetype() return empty value

need to change:

File.php line 202;

public function getMimetype()
{
if (!isset($this->mimeType)) {
$finfo = new \finfo(FILEINFO_MIME);
$mimetype = $finfo->file($this->getPathname());
$mimetypeParts = preg_split('/\s_[;,]\s_/', $mimetype);
$this->mimetype = strtolower($mimetypeParts[0]);
unset($finfo);
}

    return $this->mimetype;
}

to

public function getMimetype()
{
    if (!isset($this->mimetype)) {
        $finfo = new \finfo(FILEINFO_MIME);
        $mimetype = $finfo->file($this->getPathname());
        $mimetypeParts = preg_split('/\s*[;,]\s*/', $mimetype);
        $this->mimetype = strtolower($mimetypeParts[0]);
        unset($finfo);
    }

    return $this->mimetype;
}

maybe it's a bug

I read the source code and find src / Upload / Validation / Extension.php at line 71

array_filter($allowedExtensions, function ($val) {
     return strtolower($val);
});

I guess you just want to lower the array items.but array_filter means filter items and cannot change item's value.try this

array_walk($allowedExtensions,function(&$val){
    $val =  strtolower($val);
});

PSR-7 compliance

PSR-7 is now accepted as a recommendation and quite a few frameworks are adopting it as a standard for HTTP request and responses.

The relevant part of PSR-7 to Upload is the UploadedFileInterface. It looks like something that the File class could possibly implement, though keep in mind that the PSR-7 objects are immutable value objects.

empty input file

When an user submit a form with an empty file input (without select a file) the package should not raise an exception or populate de errors array. (File.php line 133).

Thanks.

Upload fails silently when uploading to symlinked directory

Hi,
Not sure if this is an Apache/PHP error, but I am trying to upload an image file to a symlinked directory.

Things I have checked:

  • Options +FollowSymLinks is in effect for the entire site though I don't think this affects PHP
  • File size settings are set to 10M and the file is much smaller than that; even so, that would show up in the errors, I think
  • Both the symlink and the directory it points to have full 777 permissions.

The upload fails silently and $file->getErrors() is empty.

Nothing outputs to the PHP error log either. When I check the directory, the file is not there.

Any thoughts?

Example does not work.

Hello, your example does not work :
$file = new \Upload\File('foo', $storage);

http://i.imgur.com/W5uEZ.jpg
name="kyna_imagebundle_imagetype[imageName]"


$file = new \Upload\File('kyna_imagebundle_imagetype[imageName]', $storage);
Not Work.

$file = new \Upload\File($request->files->all(), $storage);
Not Work.

foreach ($request->files->all() as $unFichier)
{
$file = new \Upload\File($unFichier, $storage);
// Not Work.

$file = new \Upload\File($unFichier['myKeyName'], $storage);
// Not Work.

}


Do you have a concrete example and functional please?
Thanks.

Drop PHP 5.3.x support

PHP 5.3 is no longer supported. Drop support for this version of PHP in the next major release.

finfo.php not found

Hi,
I am getting following issue
finfo.php not found which is being called from FileInfo->getMimetype()

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.