php实现文件上传下载
PHP 文件上传实现
使用 $_FILES 超全局变量处理上传文件,表单需设置 enctype="multipart/form-data"。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload">
<input type="submit" value="Upload">
</form>
检查文件错误代码和类型,移动临时文件到目标目录。
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
if ($_FILES["fileToUpload"]["error"] != UPLOAD_ERR_OK) {
$uploadOk = 0;
}
if (file_exists($targetFile)) {
$uploadOk = 0;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
$uploadOk = 0;
}
if ($uploadOk && move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "File uploaded successfully.";
} else {
echo "Upload failed.";
}
PHP 文件下载实现
设置正确的 HTTP 头信息强制下载文件。
$filePath = 'uploads/sample.pdf';
if (file_exists($filePath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filePath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
}
安全注意事项
验证文件类型时使用白名单方式。
$allowedTypes = ['jpg', 'png', 'pdf'];
if (!in_array($imageFileType, $allowedTypes)) {
$uploadOk = 0;
}
重命名上传文件避免目录遍历攻击。
$newFileName = uniqid() . '.' . $imageFileType;
$targetFile = $targetDir . $newFileName;
大文件上传处理
修改 php.ini 配置或使用分片上传。
upload_max_filesize = 20M
post_max_size = 20M
使用 JavaScript 分片上传示例。

// 前端分片处理逻辑
const chunkSize = 5 * 1024 * 1024; // 5MB
const file = document.getElementById('fileInput').files[0];
let offset = 0;
while (offset < file.size) {
const chunk = file.slice(offset, offset + chunkSize);
const formData = new FormData();
formData.append('file', chunk);
formData.append('name', file.name);
formData.append('offset', offset);
// 发送 AJAX 请求
offset += chunkSize;
}






