如何以 PHP 上传 500MB 以上的大文件?
可以使用 PHP 以两种方式上传大文件。下面将介绍这两种方式。
- 通过更改 php.ini 文件中的 upload_max_filesize 限制。
- 通过实现文件块上传来达到该目的,即在上传时将文件拆分为较小的块,并在上传完成时组装这些块。
可以按照如下方式更新 php.ini 文件
upload_max_filesize = 50M post_max_size = 50M max_input_time = 300 max_execution_time = 300
应避免这样做,因为这样会同时更改服务器的设置和其他项目。
更新 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
更改内联设置
<?php
// changing the upload limits
ini_set('upload_max_filesize', '50M');
ini_set('post_max_size', '50M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
// destination folder is set
$source = $_FILES["file-upload"]["tmp_name"];
$destination = $_FILES["file-upload"]["name"];
// uploaded folder is moved to the destination
move_uploaded_file($source, $destination);
?>分块
在这个过程中,会将一个大文件拆分为多个较小的部分,然后再上传。可以下载并使用“Plupload”库。
<?php
// the response function
function verbose($ok=1,$info=""){
// failure to upload throws 400 error
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;
// dealing with the chunks
$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");
}
// check if file was uploaded
if (!$chunks || $chunk == $chunks - 1) {
rename("{$filePath}.part", $filePath);
}
verbose(1, "Upload OK");
?>当尝试上传一个大小超过 500 MB 的文件时,可以成功上传该文件。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP