Wallogit.com
2017 © Pedro Pelรกez
Allow file uploads with a very low memory consumption
The class is a way to make use of PHP's built-in enable_post_data_reading setting., (*1)
The idea is to allow files upload with a very low memory consumption., (*2)
Note : due to a bug in the PHP-FPM SAPI, that package doesn't, currently, works with PHP-FPM., (*3)
Install the latest version with :, (*4)
$ composer require ecolinet/large-file-upload
enable_post_data_reading
First be sure to set enable_post_data_reading to 0 on a specific directory (e.g. public/upload/)., (*5)
There are many ways to do that,
but keep in mind that, since this directive is PHP_INI_PER_DIR, it can't be changed
with ini_set (it's logical since _POST & _FILES are processed before the script runs)., (*6)
And since it changes in many ways how PHP behaves it is not a good idea to set it globally (e.g. in php.ini)., (*7)
Here is an example with apache2 & mod_php with .htaccess overriding enabled :, (*8)
# Root of all things php_flag enable_post_data_reading 0
Note : of course it is a better idea to do that in the main configuration., (*9)
Here is an example if you are using php-fpm :, (*10)
; Root of all things enable_post_data_reading=0
Note : unlike .htaccess files, that kind of files are cached among requests (300s per default), so you can use them without the performance penalty., (*11)
Here is a small snippet of how to use it :, (*12)
$uploader = new \LargeFile\Uploader(); $parts = $uploader->read();
$parts will be an array of elements composed of :, (*13)
headers : array of all MIME headers sent by the browserfile : local filename of an uploaded filecontent : content of a posted fieldmy-app
โโโ public
ย ย โโโ upload
โโโ .htaccess
โโโ .user.ini
ย ย ย ย โโโ index.php
index.php<?php
require_once __DIR__ . '/../../vendor/autoload.php';
try {
// Get uploaded files
$uploader = new \LargeFile\Uploader();
$parts = $uploader->read();
} catch (\Exception $e) {
header('Content-type: application/json; charset=utf-8', true, 500);
echo json_encode([
'status' => "KO",
'message' => "Error !",
]);
error_log(get_class($e) . ': ' . $e->getMessage());
}
// Persist files out of tmp
foreach ($parts as $part) {
$filename = $part['headers']['filename'];
rename(
$part['file'],
__DIR__ . '/../../data/upload/' . uniqid() . '-' . $filename
);
}
// Send success status
header('Content-type: application/json; charset=utf-8', true, 200);
echo json_encode([
'status' => "OK",
'message' => "File(s) uploaded",
]);