php - PHP $_FILES 大小 总问题
问题描述
我有一个 HTML 表单,它将表单值和文件上传到 PHP 进行处理。我想做的一项检查涉及获取所有上传文件的总大小。如果 size 数组中的值都不为 0,那么我在下面的这段代码可以正常工作,但如果它们中的任何一个为 0(当文件输入留空时发生),那么由于某种原因,总数总是输出为 0。
代码:
if (!empty($_FILES['attachment'])) { //If there are attachments
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
for ($i = 0; $i < $count; $i ++) {
if (!empty($totalFileSize)){
$totalFileSize = 0;
}
//Total File Size
if ($_FILES["attachment"]["size"][$i] != 0){
$totalFileSize += ($_FILES["attachment"]["size"][$i]);
}
}
$message = $totalFileSize;
}
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
echo '<pre>'; print_r($_FILES['attachment']); echo '</pre>';
echo $totalFileSize;
exit();
输出:
Array
(
[name] => Array
(
[0] => Image Today at 10_02_27.JPG
[1] =>
)
[type] => Array
(
[0] => image/jpeg
[1] =>
)
[tmp_name] => Array
(
[0] => /tmp/phpfJo8Fl
[1] =>
)
[error] => Array
(
[0] => 0
[1] => 4
)
[size] => Array
(
[0] => 982518
[1] => 0
)
)
0
我不明白为什么如果没有 0,for 循环中的附加项可以正常工作,但如果有则不行。
解决方案
首先,如果您要使用,+=
那么您必须先初始化该变量,然后再执行第一个+=
$totalFileSize
其次,你有这条线,在循环中,如果值存在并且> 0 ,它将把值设置为零。
if (!empty($totalFileSize)){
$totalFileSize = 0;
}
所以将代码更改为
$totalFileSize = 0; // init before using `+=`
if (!empty($_FILES['attachment'])) { //If there are attachments
$count = count($_FILES['attachment']['name']);
if ($count > 0) {
for ($i = 0; $i < $count; $i ++) {
//Total File Size
if ($_FILES["attachment"]["size"][$i] != 0){
$totalFileSize += ($_FILES["attachment"]["size"][$i]);
}
}
$message = $totalFileSize;
}
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
这可以简化为
$totalFileSize = 0; // init before using `+=`
if (!empty($_FILES['attachment'])) { //If there are attachments
foreach( $_FILES['attachment']['size'] as $size){
//add up the File Sizes
$totalFileSize += $size;
}
$message = $totalFileSize;
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
甚至
if (!empty($_FILES['attachment'])) { //If there are attachments
$totalFileSize = array_sum($_FILES['attachment']['size']){
//Checks
if ($totalFileSize > 20971520){
$fileSizeError = 1;
}
}
甚至
if (!empty($_FILES['attachment'])) { //If there are attachments
if (array_sum($_FILES['attachment']['size']) > 20971520){
$fileSizeError = 1;
}
}
推荐阅读
- assembly - 源和目标的大小必须相同 (8086)
- c - C - 使用数组打印从 1 到 100 的所有素数
- java - 使用 Java 客户端检测 Prometheus 指标
- node.js - 使用谷歌云存储库的问题
- hook - Ionic 4/Angular 7 生命周期钩子每页只调用一次
- android - Dagger 2 - 了解进行字段和方法注入的不同方式
- conv-neural-network - 神经网络剪枝机制
- python-3.x - 第一列未作为索引 Pandas 导入
- python - AttributeError:未知属性颜色:Python
- hadoop - Cloudera 安装代理问题