Coder Social home page Coder Social logo

fileupload's Introduction

KISSmetrics for PHP

Build Status

KISSmetrics PHP client that doesn't overuse the singleton pattern and has a slightly better API and no built-in cron support (that's a feature). Here's how to use it:

$km = new KISSmetrics\Client('API key', KISSmetrics\Transport\Sockets::initDefault()); // Initialize

$km->identify('[email protected]')   // Identify user (always)
  ->alias('old-anonymous-cookie')  // Alias to previously anonymous user, maybe
  ->set(array('gender' => 'male')) // Set some property
  ->record('Viewed thing');        // Record an event, optionally with properties

$km->submit(); // Submit all that to KISSmetrics in one go

In case of errors this thing throws a KISSmetrics\ClientException so if you have a fire-and-forget attitude to these metrics just try/catch those. Though it's helpful when you want to make sure everything is setup correctly!

Composer

{
  "require": {
    "kissmetrics/kissmetrics-php": "~0.4.2"
  }
}

License

Licensed under the MIT license.

fileupload's People

Contributors

adelowo avatar fansanelli avatar gargron avatar gitall avatar indigo744 avatar jaketoolson avatar kaperys avatar kruglikdenis avatar milosh012 avatar netsnatch avatar peter279k avatar radmax avatar silverfire avatar snipe avatar thenovacreator avatar thers avatar

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

fileupload's Issues

PHP Warning: Creating default object from empty value

Hello,

First of all, thank you for this library. It works really well.

However, I have sometimes these kind of errors:
Severity: Warning --> Creating default object from empty value /.../vendor/gargron/fileupload/src/FileUpload/FileUpload.php 263

Looking at the code:

            } else {
                if ($upload && $upload['error'] != 0) {
                    $file = $this->getFileContainer();
                    $file->error = $this->getMessage($upload['error']); // <--- warning line is here
                    $file->errorCode = $upload['error'];
                    $this->files[] = $file;
                }

It seems that $file is not set properly (i.e. empty) hence the error when setting $file->error.

I'm not really sure what you're supposed to do in this branch, hence why I don't try to fix it and push a PR...

I hope you will find the time to look at it :)

Cheers,

Throw exception if disk is full

So for some reason when I pass big files, on some (no idea on what criteria) I get that finfo_file() doesn't recieve a file path. And indeed, when I var_dump() the $path variable passed to setTypeFromPath(), it is empty.

How to detect validation errors?

I'm evaluating this component and would like to know how code should determine if an upload was skipped and get the error that the validator detected?

In the returned files array error and errorCode are always 0, even when a validator determined that an upload is invalid.

I saw FileUpload::process() returns a new File instance. This object does not include the error detected during processing.

Processing multiple uploads

It looks like that when i set the input type file to "multiple" i get an array of stdClass when processing file. I was kinda surprised of that, since the documentation states that you have:
foreach($files as $file){ echo $file->getRealPath(); var_dump($file->isFile()); //you can call any method on an \SplFileInfo instance}
So i digged into the code, FileUpload.php -> processAll() has this:

$this->files[] = (object)(array)$this->process( $tmp_name, $upload['name'][$index], $size ? $size : $upload['size'][$index], $upload['type'][$index], $upload['error'][$index], $index, $content_range );

I find it very unconvenient to cast an SplFileInfo to array and then back to sdtClass. Woudn't it much better to just keep the original object instance?

The fix was here: #25 but i think that's not a good solution

Edit: a more deep inspection made me question about this:
protected function process($tmp_name, $name, $size, $type, $error, $index = 0, $content_range = null) { $file = $this->fileContainer = new File($tmp_name);

I think that to fix the problem once for all we shoudn't replace $this->fileContainer with the new file instance, instead we could just replace it just once when $index == 0, so that we keep all the mechanics for single upload but we keep the strong SplFileInfo for multiple uploads since then we can fix $this->files[] = (object)(array)$this->process( with $this->files[] = $this->process(

Please tell me if I'm missing some of the logic behind that.

Multiple upload

I've seen closed issue with the same title, but it seems no one have problems uploading multiple files.

I'm pretty sure HTML doesn't require a name with [] such as files[] in this sample code <input class="form-control" type="file" name="files[]" value="" multiple/> if we want to upload multiple files.

Just to point out that there is no where in your docs stating the need for an [].

Great library though. Thumbs up!

Store the original file name in File class

I could implement the feature in subject, but before I'd like to hear some feedback... I'm using the random name generator, but I still need the original file name. To workaround the lack of this feature I am looping files array returned by processAll() method while reading the value from the global one: $_FILES['foo']['name'][$i]. What do you think?

get the file name

list($files, $headers) = $fileupload->processAll();
echo json_encode(['files' => $files]);

Two files were uploaded.
file name visible only for validation file error:

{"files":[{"error":"Filetype not allowed","errorCode":0,"completed":false,"name":"header-image.jpg","size":72193},{"error":0,"errorCode":0,"completed":true,"size":2254}]}

How to get the file name?

Trying to access array offset on value of type null

PHP Version: 7.4
Fileupload Version: 1.5.1

When using the Random Filename generator I get this notice:

Notice: Trying to access array offset on value of type null in .....\vendor\gargron\fileupload\src\FileUpload\FileNameGenerator\Random.php on line 70

Which is this line of code:
$uploaded_bytes = Util::fixIntegerOverflow(intval($content_range[1]));

Translations

Is the only way to translate to extend and override at the moment or is there a better way?
Thanks.

Auto create store dir

$pathresolver = new FileUpload\PathResolver\Simple('/my/uploads/dir');

Supporting auto create dir /my/uploads/dir will be nice.

Tag a new release

Last release was Feb 2014. There have been a lot of commits since then and I'm currently using dev-master in my composer file. Is there something else that needs to be done before next release?

Non-working plugin

  1. Code example provides only POST-request processing.
    GET-requests with validation file status not processed (/upload?file=8562-172094-181.pdf). No code for that provided with plugin.
  2. File-type of the chunks checks working incorrect
    first chunk goes with responce:
    [{"error":0,"errorCode":0,"completed":false,"size":512000}]
    second and other with:
    [{"error":"Filetype not allowed","errorCode":0,"completed":false,"name":"8562-172094-181.pdf","size":1875851}]
    So, need to use https://github.com/blueimp/jQuery-File-Upload/blob/master/server/php/UploadHandler.php instead. Sorry.

Fails validate when php error is string

I process array of files. Php upload error is string(1) "0", but in validate() you check ($error !== 0) and my upload failed.

And is see that you not show any validate error messages, i think it may be very useful

File name

How do I pass in a name manually ?
Example: If I want the new file to be named "newFileName1", and not have it generate a random string with FileNameGenerator (Simple or MD5).

setMessages reorder messages key

From http://php.net/array_merge

Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.

In FileUpload.php used UPLOAD_ERR_* integer constants as messages keys.
So if I set my own messages I got this:

Array
(
[0] => The uploaded file exceeds the upload_max_filesize directive in php.ini
[1] => The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form
[2] => The uploaded file was only partially uploaded
[3] => No file was uploaded
[4] => Missing a temporary folder
[5] => Failed to write file to disk
[6] => A PHP extension stopped the file upload
[7] => The upload file exceeds the post_max_size or the upload_max_filesize directives in php.ini
[8] => Размер файла превышает максимальный размер заданый в php.ini
[9] => Размер файла превышает максимальный размер переданный в форме
[10] => Файл был загружен не полностью
[11] => Файл не был загружен
[12] => Отсутствует временный каталог
[13] => Ошибка записи на диск
[14] => A PHP extension stopped the file upload
[15] => Размер файла превышает максимальный размер
)

getRealPath does not work

At least not for me. When I try the example from the readme, I always get that getRealPath() is not defined on stdClass

Undefined variables

I am getting the following two warnings when I upload chunked files

Notice: Undefined variable: completed in [...]/vendor/gargron/fileupload/src/FileUpload/FileUpload.php on line 360

Notice: Undefined property: FileUpload\File::$size in [...]/vendor/gargron/fileupload/src/FileUpload/FileUpload.php on line 579

Cheers,
Patrick.

Invalid $files after processAll()

list($files, $headers) = $fileupload->processAll();

While uploading multiple image files, the $files array I received was wrong.
It had the same value (last image data) for all array indices.

Can anyone please confirm if this is the case with everyone or just me ?

In case it's for everyone, this is a major issue and I have found a solution which I would be happy to share.

PHP 7.1 incompatibility

Due change in handling strings in PHP 7.1

New E_WARNING and E_NOTICE errors have been introduced when invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. An E_NOTICE is emitted when the string begins with a numeric value but contains trailing non-numeric characters, and an E_WARNING is emitted when the string does not contain a numeric value.

There is now E_NOTICE in function getConfigBytes. $val variable has to be stripped of last character (k, M, etc.) to be valid for numeric computations.

insert into database

hi
great libs! thanks!
I have use jquery file upload with UploadHanlder.php default file, adding file into database when a file is uploaded.
I guess how to do the same with this class: insert file into mysql table after upload, and delete from a mysql table when a file is deleted.

callback will be ideal, but seem not yet implmented or yes?

thanks

add base64 functonality

Hi, amazing class.

Is it possible to add base64 decode in the future to make it compatible with Croppie.js or is there a way i can use this script and do the decoding i would love to know.

Also another idea could be a watermark functionality.

Thanks. Amazing class!

ErrorException: "A non well formed numeric value encountered" in PHP 7.1

When using this library on PHP 7.1 an exception is thrown:
A non well formed numeric value encountered

It is thrown from FileUpload::getConfigBytes method:

protected function getConfigBytes($val)
    {
        $val  = trim($val);
        $last = strtolower($val[strlen($val) - 1]);

        switch ($last) {
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }

        return $this->fixIntegerOverflow($val);
    }

My set up that triggers this error (in a Laravel 5.2 app):

        $sizeValidator = new \FileUpload\Validator\SizeValidator((4*1024*1024));

        // Simple path resolver, where uploads will be put
        $pathResolver = new \FileUpload\PathResolver\Simple(public_path() . '/uploads/' . $uploadPath);

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

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

Backtrace:

at FileUpload->getConfigBytes('4M') in FileUpload.php line 532
at FileUpload->validate('/tmp/php28Mk6i', object(File), '0', '0') in FileUpload.php line 367
at FileUpload->process('/tmp/php28Mk6i', 'blank_keyboard_2012_front.jpg', '63221', 'image/jpeg', '0', '0', null) in FileUpload.php line 288
at FileUpload->processAll() in MediaAdminController.php line 207

file name of upload completed

#59

list($files, $headers) = $fileupload->processAll();
echo json_encode(['files' => $files]);

Two files were uploaded.
file name visible only for validation file error:

{"files":[{"error":"Filetype not allowed","errorCode":0,"completed":false,"name":"header-image.jpg","size":72193},{"error":0,"errorCode":0,"completed":true,"size":2254}]}

This will work only as follows:

        foreach($files as $file) {
            if ($file->completed) { // check if the upload was completed
                echo $file->getFilename();
            }
        }       

But how can I get the file names for both completed/uncompleted?

Version 2

While the library works as expected, the motivation for a 2.0 are

  • PHP version support (I created #36 last year but had to back down a bit).. 2.0 is >=7.0

  • Storage abstraction : We currently maintain our own abstractions, interfaces and a local adapter but there are battle tested community packages that have stood out over the years.. Flysystem and Gaufrette comes to mind.. Tracking issues -> #1 ... Plus we get access to multiple adapters, Flysystem for example has about 10 adapters (Dropbox, s3 e.t.c)

  • Code clean up ---> The original author wrote this version in the days of 5.3 (pre PSR), The community has agreed on PSR2 but some part of the lib don't conform hence leading to multiple coding standards... While I have spent quite some time fixing those, all isn't done since I wouldn't like to move code around just for PSR conformation without fixing something in there.
    Another thing some part of the codebase uses snake case, others camelCase

  • Many more

Chunked file last chuk

I think the resulting file object after processing should contain information about wether the last chunk has been uploaded.

Enhancement: FileNameGenerator\Hash

If I may suggest a nice enhancement.

Get rid of FileNameGenerator\MD5 class and add a FileNameGenerator\Hash class which accept:

  1. A hashing algorithm name, as expected by the hash() function (PHPDoc), and as listed by hash_algos() (PHPDoc)
  2. An optional salt string, for avoiding collision attack (e.g. in case the hashed name is made public)
  3. An optional allowOverride boolean

This will allow a lot more flexibility. What do you think?

callback

hello

how can i use Callbacks functions with sample?

thank's

why use HTTP_CONTENT_RANGE to judge if chunked

example
request header
Range: bytes=0-2000

response header
Content-Range: bytes 0-2000/4932

but the library use $this->server['HTTP_CONTENT_RANGE'] in FileUpload.php to judge if chunked, is it correct?

Chucked upload not working.

Only the first chance in a chucked upload gets uploaded. Here is my code:

$extension = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
    
    
    // Simple validation (max file size 2MB and only two allowed mime types)
    $validator = new FileUpload\Validator\Simple('200M', [
        'video/x-flv', // .flv
        'video/mp4', // .mp4
        'application/x-mpegURL', // iphone .mp4, .mpu
        'video/MP2T', // iphone .ts
        'video/3gpp', // .3gp videos
        'video/3gpp2', // .3gp, .3gp2, .3gpp videos
        'video/quicktime', // .mov
        'video/x-msvideo', // .avi
        'video/webm', // .webm
        'video/webm', // .webm
        'video/ogg', // .ogg
        'video/x-matroska', // .mkv
        'video/x-ms-wmv' // .wmv
    ]);

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

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

    // FileUploader itself
    $fileupload = new FileUpload\FileUpload($_FILES['video'], $_SERVER);
    
    $filename = time() . preg_replace('/[^a-zA-Z0-9_]+/', '_',  preg_replace('/[.]' .$extension. '$/', '', trim($_FILES['video']['name'])));
    $filenamegenerator = new FileUpload\FileNameGenerator\Custom($filename  . '.mp4');

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

    /*// 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]);
    
    
    $fileupload->addCallback('completed', function(FileUpload\File $file) {
echo $file->getRealPath();
});

Getting Internerla Server error issue when the file size is higher than my maxChunckSize.

Here is my Javascript:

$('#fileupload').fileupload({
    maxChunkSize: 10000000, // 10 MB
    add: function (e, data) {
        var that = this;
        $.getJSON('server/php/', {file: data.files[0].name}, function (result) {
            var file = result.file;
            data.uploadedBytes = file && file.size;
            $.blueimp.fileupload.prototype
                .options.add.call(that, e, data);
        });
    }
});

How to put file name and other fields in the JSON to work with jQuery File Upload Basic Plus UI example?

Hello,
Sorry for the dumb question
I'd like to use this package with Basic Plus UI version of jQuery File Upload. I noticed that json_encode(['files' => $files]) does not return all the values I need, i.e the file name, url or thumbnailUrl (these are referenced in the JavaScript template part of Basic Plus UI example). Instead, I get something like this: {"files":[{"error":0,"errorCode":0,"completed":true,"size":775702}]}, missing some important informations

How can I put all the other info I need in the JSON?
Thank you in advance!

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.