我从网页上传中获取多个文件。 我现在可以检查文件是否具有正确的特定扩展名,我现在还可以检查文件的大小是否在允许的范围内。
但是我还需要验证上传时没有遇到错误。
在将文件上传到数据库服务器之前,我必须检查$_FILES['file']['error']的所有值是否都等于0。在执行上传代码之前,我应该如何检查 $_FILES['file']['error'] (这是一个数组)中的所有值是否等于 0?
这是我的完整代码:
if(isset($_POST['submit'])) {
$allowed = array('jpg','jpeg','png','pdf','xlsx','docs','xls','docx','ppt');
$file_name_checking = $_FILES['file']['name'];
$file_size_checking = $_FILES['file']['size'];
$file_error_checking = $_FILES['file']['error']; //this is the array to be checked
$file_name_check_actual_ext = array();
foreach ($file_name_checking as $extension_files) {
$extension_actual = explode('.', $extension_files);
$file_actual_Ext = strtolower(end($extension_actual));
$file_name_check_actual_ext[] = $file_actual_Ext;
}
$file_name_check_ext = '';
$file_name_check_ext = !array_diff($file_name_check_actual_ext, $allowed);
if($file_name_check_ext === true) {
if(max($file_size_checking) < 1000000) {
//my upload code
foreach ($_FILES['file']['tmp_name'] as $key => $value) {
$file_name = $_FILES['file']['name'][$key];
$file_tmp_name = $_FILES['file']['tmp_name'][$key];
$file_size = $_FILES['file']['size'][$key];
$file_error = $_FILES['file']['error'][$key];
$file_type = $_FILES['file']['type'][$key];
$file_ext = explode('.', $file_name);
$file_name_original = pathinfo($file_name, PATHINFO_FILENAME);
$file_actual_Ext = strtolower(end($file_ext));
$file_name_new = uniqid('',true).".".$file_actual_Ext;
$file_destination = '../uploads/'.$file_name_new;
$result = move_uploaded_file($file_tmp_name, $file_destination);
$query = "INSERT INTO file_storage (
file_name,
file_size,
file_type,
file_name_unique,
file_ext
)
VALUES (
:file_name,
:file_size,
:file_type,
:file_name_unique,
:file_ext
)
";
$stmt=$pdo->prepare($query);
$stmt->bindParam(":file_name", $file_name_original);
$stmt->bindParam(":file_size", $file_size);
$stmt->bindParam(":file_type", $file_type);
$stmt->bindParam(":file_name_unique", $file_name_new);
$stmt->bindParam(":file_ext", $file_actual_Ext);
$stmt->execute();
}
if ($result) {
echo "Files uploaded successfully!";
}
}
else {
echo "File Size is too large!";
}
}
else {
echo "Please check the exension of files";
}
}
在执行上传代码之前我需要另一个 if 语句。
您可以创建一个方法来验证数组是否包含全零:
<?php
function arrayContainsOnlyZero($array) {
// Filter the array, keeping only non-zero values
$filteredArray = array_filter($array, function($value) {
return $value !== 0;
});
// Check if the filtered array is not empty
return empty($filteredArray);
}
// Example usage
$array1 = [0, 0, 0, 0];
$array2 = [0, 1, 0, 2];
$array3 = [0, 0, 0, 0.1];
echo "array1 contains all 0: " . arrayContainsOnlyZero($array1) . "\n";
echo "array2 contains all 0: " . arrayContainsOnlyZero($array2) . "\n";
echo "array3 contains all 0: " . arrayContainsOnlyZero($array3) . "\n";
你可以检查这个PHP沙箱来检查