在Web开发中,文件上传是常见且重要的功能。PHP通过$_FILES全局变量实现文件的接收和管理。上传流程通常包括客户端提交文件,服务器保存到临时目录,验证文件合法性,最后将文件移动到指定目录完成上传。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="上传文件">
</form>
<?php
$fileName = $_FILES['file']['name'];
$fileSize = $_FILES['file']['size'];
$fileTmp = $_FILES['file']['tmp_name'];
$fileType = $_FILES['file']['type'];
?>
<?php
$allowedTypes = ['image/jpeg', 'image/png']; // 允许上传的文件类型
$maxSize = 2 * 1024 * 1024; // 最大允许上传文件大小,2MB
if (in_array($fileType, $allowedTypes) && $fileSize <= $maxSize) {
$destination = 'uploads/' . $fileName;
move_uploaded_file($fileTmp, $destination);
echo '文件上传成功!';
} else {
echo '不允许上传该类型的文件或文件大小超过限制!';
}
?>
文件下载是Web应用中的另一个关键功能。客户端通过发送请求,服务器读取文件并通过HTTP响应将文件传输给客户端。设置合理的HTTP头部确保文件能够被正确下载和保存。
<span class="fun"><a href="download.php?file=文件名">下载文件</a></span>
<?php
$filePath = 'path/to/file/' . $_GET['file'];
if (file_exists($filePath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filePath));
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
} else {
echo '文件不存在!';
}
?>
通过合理的文件类型和大小校验,结合正确的文件移动及下载头设置,能够有效保障文件上传与下载的安全性和稳定性。希望本文的讲解对PHP开发者理解底层文件处理原理有所帮助,并能在实际项目中灵活应用。