php实现文件上传下载
文件上传实现
在PHP中实现文件上传需要使用$_FILES超全局变量处理上传的文件数据。确保HTML表单设置enctype="multipart/form-data"属性。
HTML表单示例:
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload">
<input type="submit" value="Upload">
</form>
PHP处理脚本(upload.php):
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$fileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));
// 检查文件是否已存在
if (file_exists($targetFile)) {
echo "文件已存在";
$uploadOk = 0;
}
// 限制文件大小(5MB)
if ($_FILES["fileToUpload"]["size"] > 5000000) {
echo "文件太大";
$uploadOk = 0;
}
// 允许特定文件类型
$allowedTypes = ["jpg", "png", "jpeg", "gif"];
if (!in_array($fileType, $allowedTypes)) {
echo "只允许JPG, JPEG, PNG和GIF文件";
$uploadOk = 0;
}
// 检查上传标志并移动文件
if ($uploadOk == 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "文件上传成功";
} else {
echo "文件上传失败";
}
}
文件下载实现
实现文件下载可以通过设置适当的HTTP头强制浏览器下载文件,而不是在浏览器中打开。
PHP下载脚本示例(download.php):
$file = 'uploads/' . basename($_GET['file']);
$filepath = realpath($file);
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));
flush();
readfile($filepath);
exit;
} else {
http_response_code(404);
echo "文件不存在";
}
安全注意事项
验证文件类型不应仅依赖文件扩展名,可以使用finfo_file()函数检测实际MIME类型:
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["fileToUpload"]["tmp_name"]);
finfo_close($finfo);
限制上传目录的访问权限,确保目录不可执行:
chmod($targetDir, 0755);
考虑重命名上传文件以避免文件名冲突和安全问题:
$newFilename = uniqid() . '.' . $fileType;
$targetFile = $targetDir . $newFilename;
大文件上传处理
对于大文件上传,可能需要调整PHP配置:
ini_set('upload_max_filesize', '100M');
ini_set('post_max_size', '100M');
ini_set('max_execution_time', '300');
或者通过分片上传技术实现,使用JavaScript将文件分块后分别上传。






