Maximum Upload

This commit is contained in:
lionel 2021-01-25 15:27:10 +01:00
parent 81c5cfa478
commit 360a7c112f
2 changed files with 50 additions and 12 deletions

39
fonction.php Normal file
View File

@ -0,0 +1,39 @@
<?php
function formatBytes($size, $precision = 2)
{
$base = log($size, 1024);
$suffixes = array('', 'KiB', 'MiB', 'GiB', 'TiB');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
function convertToBytes(string $from): ?int {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$number = substr($from, 0, -2);
$suffix = strtoupper(substr($from,-2));
//B or no suffix
if(is_numeric(substr($suffix, 0, 1))) {
return preg_replace('/[^\d]/', '', $from);
}
$exponent = array_flip($units)[$suffix] ?? null;
if($exponent === null) {
return null;
}
return $number * (1024 ** $exponent);
}
function folderSize($dir)
{
$size = 0;
foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $each) {
$size += is_file($each) ? filesize($each) : folderSize($each);
}
return $size;
}
?>

View File

@ -4,13 +4,16 @@ error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
include 'fonction.php';
$max_size = convertToBytes('2GB');
$root = $_SERVER["DOCUMENT_ROOT"];
$target_dir = "$root/uploads/";
if(! isset($_FILES["file"])) {
header("HTTP/1.1 400 No file Upload");
//trigger_error("No file Upload",E_USER_ERROR);
exit();
}
@ -18,9 +21,15 @@ $file = $_FILES["file"];
$name = basename($file["name"]);
$size = basename($file["size"]);
if ((folderSize($target_dir) + $size) > $max_size) {
header("HTTP/1.1 400 " . $name . " file too large");
exit();
}
if (! extension_loaded('mbstring')) {
header("HTTP/1.1 400 Bad encode");
header("HTTP/1.1 500 php module missing");
exit();
}
@ -29,9 +38,6 @@ if(! mb_check_encoding($name)) {
exit();
}
$size = basename($file["size"]);
$target_file = $target_dir.$name;
// Check if file already exists
@ -48,11 +54,4 @@ else {
}
}
function formatBytes($size, $precision = 2)
{
$base = log($size, 1024);
$suffixes = array('', 'KiB', 'MiB', 'GiB', 'TiB');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
?>