PHP: Cách upload nhiều file cùng lúc
Trước tiên ta tạo một FORM như sau:
<form action="demo_upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="file[]" multiple />
<p><input type="submit" name="upload" value="Upload File"/></p>
</form>
Giải thích FORM:
- enctype=”multipart/form-data”: dữ liệu được chia ra làm nhiều phần, dùng để upload file.
- method=”POST”: phương thức gửi dữ liệu là post.
- Một input có type = "file" và có tên là một mảng file[], lưu ý là phải có thuộc tính multiple để cho phép chọn nhiều file cùng một lúc.
- Nút lệnh Submit để gửi dữ liệu.
Còn đây là đoạn code của file demo_upload.php:
if (isset($_POST[‘submit’])){
$name = array();
$tmp_name = array();
$error = array();
$ext = array();
$size = array();
foreach ($_FILES[‘file’][‘name’] as $file) {
$name[] = $file;
}
foreach ($_FILES[‘file’][‘tmp_name’] as $file){
$tmp_name[] = $file;
}
foreach ($_FILES[‘file’][‘error’] as $file){
$error[] = $file;
}
foreach ($_FILES[‘file’][‘type’] as $file){
$ext[] = $file;
}
foreach ($_FILES[‘file’][‘size’] as $file){
$size[] = round($file/1024,2);
} //Phần này lấy giá trị ra từng mảng nhỏ
echo “Tổng số file được tải lên: “.count($name).”<br>”;
echo “<table style=’color: white;’>\n<thead>\n<th>Tên file</th>\n<th>Loại</th>\n<th>Kích thước</th>\n<th>Thư mục</th>”;
for ($i=0;$i<count($name);$i++){
if ($error[$i] > 0){
echo “Lỗi: ” . $error[$i];
}elseif ($ext[$i]!=’application/save’) {
echo “File không được hổ trợ”.$ext[$i];
}else {
$temp = preg_split(‘/[\/\\\\]+/’, $name[$i]);
$filename = $temp[count($temp)-1];
$upload_dir = “../download/”;
$upload_file = $upload_dir . $filename;
if (file_exists($upload_file)) {
echo ‘File đã tồn tại’;
} else {
if ( move_uploaded_file($tmp_name[$i], $upload_file) ) {
echo “<tr>\n<td>”.$name[$i].”</td>\n”;
echo ‘<td>’.$ext[$i].”</td>\n”;
echo ‘<td>’.$size[$i].” kB</td>\n”;
echo ‘<td>’.$upload_file.”</td>\n</tr>”;
$date = date(“d-m-Y”);
@mysqli_connect(‘stringhost’, ’stringUsername’, ’stringPass’, ’stringDatabase’);
@mysqli_query($conn, ”INSERT INTO `tablename` VALUES (null,'{$name[$i]}’,'{$size[$i]}’,’$upload_dir’,’$date’,0)”) or die(“Bi loi them du lieu”.mysqli_error($conn));
@mysqli_close($conn);
} else echo ‘loi’;
}
}//End khoi cau lenh up file va them vao CSDL;
}//End vong lap for cho tat ca cac file;
echo ‘</table>’;
}
Giải thích đoạn mã:
- Trước tiên ta lấy từng mảng nhỏ trong mảng $_FILES[‘file’] ra thành các mảng nhỏ là $name[], $tmp_name[], $type[], $size[] và $error[].
- Tiếp theo ta tạo một vòng lặp cho các phần tử của mảng vừa mới tạo, biến chạy $i chạy từ 0 tới count($name)-1;
- Từ đây ta sẽ viết tiếp lệnh up file và thêm dữ liệu vào CSDL:
- $temp = preg_split(‘/[\/\\\\]+/’, $name[$i]); $filename = $temp[count($temp)-1]: hai câu lệnh này dùng để lấy tên file;
- $upload_dir = “../download/”: thư mục upload của mình là ../upload (chỉnh sửa để phù hợp với trường hợp của bạn);
- move_uploaded_file($tmp_name[$i], $upload_file): dòng lệnh này dùng để up file lên host;
- và cuối cùng là ghi dữ liệu vào CSDL mySQL với khối lệnh sau: @mysqli_connect(‘stringhost’,’stringUsername’,’stringPass’,’stringDatabase’);
@mysqli_query($conn,”INSERT INTO `tablename` VALUES (null,'{$name[$i]}’,'{$size[$i]}’,’$upload_dir’,’$date’,0)”) or die(“Bi loi them du lieu”.mysqli_error($conn));
@mysqli_close($conn);
- Và để tiện quan sát kết quả ta sẽ cho hiển thị dưới dạng bảng với khối lệnh:
echo “<table>”;
echo “<tr>\n<td>”.$name[$i].”</td>\n”;
echo ‘<td>’.$ext[$i].”</td>\n”;
echo ‘<td>’.$size[$i].” kB</td>\n”;
echo ‘<td>’.$upload_file.”</td>\n</tr>”;