php实现文件上传
文件上传的基本实现
使用PHP实现文件上传需要处理HTML表单和服务器端脚本。HTML表单需要设置enctype="multipart/form-data"属性,PHP通过$_FILES超全局数组接收上传的文件。
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload File" name="submit">
</form>
PHP脚本中检查文件是否存在并处理上传:
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["fileToUpload"]["name"]);
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $targetFile)) {
echo "The file has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
文件验证与安全措施
上传文件时需验证文件类型和大小,防止恶意文件上传。检查文件的MIME类型和扩展名是否合法。
$allowedTypes = ['image/jpeg', 'image/png'];
$fileType = $_FILES["fileToUpload"]["type"];
if (!in_array($fileType, $allowedTypes)) {
die("Invalid file type.");
}
$maxFileSize = 2 * 1024 * 1024; // 2MB
if ($_FILES["fileToUpload"]["size"] > $maxFileSize) {
die("File size exceeds the limit.");
}
生成唯一文件名避免冲突:
$fileExtension = pathinfo($_FILES["fileToUpload"]["name"], PATHINFO_EXTENSION);
$newFileName = uniqid() . '.' . $fileExtension;
$targetFile = $targetDir . $newFileName;
错误处理与反馈
检查上传过程中的错误代码,提供详细的错误反馈。
if ($_FILES["fileToUpload"]["error"] !== UPLOAD_ERR_OK) {
switch ($_FILES["fileToUpload"]["error"]) {
case UPLOAD_ERR_INI_SIZE:
die("The uploaded file exceeds the upload_max_filesize directive in php.ini.");
case UPLOAD_ERR_FORM_SIZE:
die("The uploaded file exceeds the MAX_FILE_SIZE directive in the HTML form.");
case UPLOAD_ERR_PARTIAL:
die("The uploaded file was only partially uploaded.");
case UPLOAD_ERR_NO_FILE:
die("No file was uploaded.");
case UPLOAD_ERR_NO_TMP_DIR:
die("Missing a temporary folder.");
case UPLOAD_ERR_CANT_WRITE:
die("Failed to write file to disk.");
case UPLOAD_ERR_EXTENSION:
die("A PHP extension stopped the file upload.");
}
}
多文件上传处理
支持同时上传多个文件,使用数组形式的文件输入名称。
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple>
PHP脚本中遍历处理每个文件:
foreach ($_FILES["filesToUpload"]["tmp_name"] as $key => $tmpName) {
$targetFile = $targetDir . basename($_FILES["filesToUpload"]["name"][$key]);
if (move_uploaded_file($tmpName, $targetFile)) {
echo "The file " . htmlspecialchars(basename($_FILES["filesToUpload"]["name"][$key])) . " has been uploaded.<br>";
}
}






