文件上传是Web开发中的一个常见功能,允许用户通过表单上传文件到服务器。PHP提供了内置的函数来处理文件上传,如$_FILES
全局变量和move_uploaded_file()
函数。
以下是一个简单的PHP文件上传函数封装示例:
<?php
function uploadFile($fileInputName, $uploadPath, $maxSize = 1048576) {
// 检查是否有文件上传
if (isset($_FILES[$fileInputName])) {
$file = $_FILES[$fileInputName];
// 检查文件大小
if ($file['size'] > $maxSize) {
return "文件大小超过限制";
}
// 检查文件类型
$fileType = mime_content_type($file['tmp_name']);
if (!in_array($fileType, ['image/jpeg', 'image/png', 'application/pdf'])) {
return "不支持的文件类型";
}
// 生成新的文件名
$newFileName = uniqid() . '.' . pathinfo($file['name'], PATHINFO_EXTENSION);
$uploadFilePath = $uploadPath . '/' . $newFileName;
// 移动上传的文件到目标路径
if (move_uploaded_file($file['tmp_name'], $uploadFilePath)) {
return "文件上传成功,新文件名:" . $newFileName;
} else {
return "文件上传失败";
}
} else {
return "没有文件被上传";
}
}
// 使用示例
$result = uploadFile('file', '/path/to/upload/directory');
echo $result;
?>
php.ini
文件中的upload_max_filesize
和post_max_size
来调整。mime_content_type()
函数来检查文件类型,并进行相应的限制。move_uploaded_file()
函数的返回值。通过以上封装函数和示例代码,可以方便地实现文件上传功能,并确保上传的文件符合预期的要求。
领取专属 10元无门槛券
手把手带您无忧上云