File lớn có thể upload bằng PHP theo hai cách. Cả hai thảo luận dưới:
- Thay đổi limit upload_max_filesize trong php.ini.
- Triển khai upload file chunk, chia upload thành mảnh nhỏ và ghép lại khi hoàn tất.
Cập nhật php.ini như sau:
upload_max_filesize = 50M post_max_size = 50M max_input_time = 300 max_execution_time = 300
Nên tránh vì thay đổi setting server và dự án khác.
Cập nhật file htaccess
php_value upload_max_filesize 50M php_value post_max_size 50M php_value max_input_time 300 php_value max_execution_time 300
Thay đổi setting inline:
<?php
// thay đổi limit upload
ini_set('upload_max_filesize', '50M');
ini_set('post_max_size', '50M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
// thư mục đích
$source = $_FILES["file-upload"]["tmp_name"];
$destination = $_FILES["file-upload"]["name"];
// move uploaded file
move_uploaded_file($source, $destination);
?>
Chunking (chia mảnh)
Quy trình này chia file lớn thành phần nhỏ rồi upload. Thư viện 'Plupload' có thể tải và dùng.
<?php
// response function
function verbose($ok=1, $info=""){
// upload thất bại throw 400
if ($ok==0) { http_response_code(400); }
die(json_encode(["ok"=>$ok, "info"=>$info]));
}
// invalid upload
if (empty($_FILES) || $_FILES['file']['error']) {
verbose(0, "Failed to move uploaded file.");
}
// upload destination
$filePath = __DIR__ . DIRECTORY_SEPARATOR . "uploads";
if (!file_exists($filePath)) {
if (!mkdir($filePath, 0777, true)) {
verbose(0, "Failed to create $filePath");
}
}
$fileName = isset($_REQUEST["name"]) ? $_REQUEST["name"] : $_FILES["file"]["name"];
$filePath = $filePath . DIRECTORY_SEPARATOR . $fileName;
// xử lý chunk
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;
$out = @fopen("{$filePath}.part", $chunk == 0 ? "wb" : "ab");
if ($out) {
$in = @fopen($_FILES['file']['tmp_name'], "rb");
if ($in) {
while ($buff = fread($in, 4096)) { fwrite($out, $buff); }
} else {
verbose(0, "Failed to open input stream");
}
@fclose($in);
@fclose($out);
@unlink($_FILES['file']['tmp_name']);
} else {
verbose(0, "Failed to open output stream");
}
// kiểm tra file upload xong
if (!$chunks || $chunk == $chunks - 1) {
rename("{$filePath}.part", $filePath);
}
verbose(1, "Upload OK");
?>
Khi file > 500 MB thử upload, nó upload thành công.