php - 使用 PHP 上传多个文件

标签 php html

i want to upload multiple file upload.It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. I am going to show you how to upload multiple file with PHP and basic HTML form but something missing it (multiple file is not upload)

我尝试了下面的代码

HTML 代码

<html>
<head>

<?php

if (isset($message)) {
foreach ($message as $msg) {
printf(“<p class=’status’>%s</p></ br>\n”, $msg);
}
}
# success message
if($count !=0){
printf(“<p class=’status’>%d files added successfully!</p>\n”, $count);
}
?>
<title>Multiple File upload with PHP</title>
</head>
<body>
<form action=”” method=”post” enctype=”multipart/form-data”>
<input type=”file” id=”file” name=”files” multiple=”multiple” accept=”image/*” />
<input type=”submit” value=”Upload!” />
</form>
</body>
</html>

PHP 脚本

<?php
$valid_formats = array(“jpg”, “png”, “gif”, “zip”, “bmp”);
$max_file_size = 1024*5000; //100 kb
$path = “uploads/”; // Upload directory
$count = 0;

if(isset($_POST) and $_SERVER[‘REQUEST_METHOD’] == “POST”){
// Loop $_FILES to exeicute all files
foreach ($_FILES[‘files’][‘name’] as $f => $name) {
if ($_FILES[‘files’][‘error’][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES[‘files’][‘error’][$f] == 0) {
if ($_FILES[‘files’][‘size’][$f] > $max_file_size) {
$message[] = “$name is too large!.”;
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = “$name is not a valid format”;
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES[“files”][“tmp_name”][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}

?>

最佳答案

将输入文件名替换为files[],而不是files,请参阅以下表单示例:

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
    <input type="submit" value="Upload!" />
</form>

关于php - 使用 PHP 上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40129388/

相关文章:

php - 为什么 if (xmlHttp.readyState == 4) 会出错

php - 使用 Centos7 和 Apache 在 PHP 中执行的命令无法连接到网络?

javascript - 将 document.write 转换为 getElementById/innerHTML

html - 中心页脚固定在底部 IE

php - 通过更改网站语言来更改 Logo 图像

javascript - MySQL循环只能删除第一条数据?

php - WooCommerce - 使用 "save_post" Hook 更新订单时发送通知电子邮件

javascript - 边框不显示文本,填充框不正确显示

javascript - 多层 ul/li 菜单错误

java - 如何从选项标签返回值