|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace AppUtils\FileHelper; |
|
6
|
|
|
|
|
7
|
|
|
class UploadFileSizeInfo |
|
8
|
|
|
{ |
|
9
|
|
|
private static int $max_size = -1; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Retrieves the maximum allowed upload file size, in bytes. |
|
13
|
|
|
* Takes into account the PHP ini settings <code>post_max_size</code> |
|
14
|
|
|
* and <code>upload_max_filesize</code>. Since these cannot |
|
15
|
|
|
* be modified at runtime, they are the hard limits for uploads. |
|
16
|
|
|
* |
|
17
|
|
|
* NOTE: Based on binary values, where 1KB = 1024 Bytes. |
|
18
|
|
|
* |
|
19
|
|
|
* @return int Will return <code>-1</code> if no limit. |
|
20
|
|
|
*/ |
|
21
|
|
|
public static function getFileSize() : int |
|
22
|
|
|
{ |
|
23
|
|
|
if (self::$max_size < 0) |
|
24
|
|
|
{ |
|
25
|
|
|
self::resolveSize(); |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
return self::$max_size; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
private static function resolveSize() : void |
|
32
|
|
|
{ |
|
33
|
|
|
// Start with post_max_size. |
|
34
|
|
|
$post_max_size = self::parse_size(ini_get('post_max_size')); |
|
35
|
|
|
|
|
36
|
|
|
if ($post_max_size > 0) { |
|
37
|
|
|
self::$max_size = $post_max_size; |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
// If upload_max_size is less, then reduce. Except if upload_max_size is |
|
41
|
|
|
// zero, which indicates no limit. |
|
42
|
|
|
$upload_max = self::parse_size(ini_get('upload_max_filesize')); |
|
43
|
|
|
|
|
44
|
|
|
if ($upload_max > 0 && $upload_max < self::$max_size) { |
|
45
|
|
|
self::$max_size = $upload_max; |
|
46
|
|
|
} |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
private static function parse_size(string $size) : int |
|
50
|
|
|
{ |
|
51
|
|
|
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. |
|
52
|
|
|
$result = (float)preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. |
|
53
|
|
|
|
|
54
|
|
|
if($unit) |
|
55
|
|
|
{ |
|
56
|
|
|
// Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. |
|
57
|
|
|
return (int)round($result * (1024 ** stripos('bkmgtpezy', $unit[0]))); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
return (int)round($result); |
|
61
|
|
|
} |
|
62
|
|
|
} |
|
63
|
|
|
|