功能清单
- 按日期 (Ymd) 自动创建上传目录
- 校验文件类型(图片/Flash)、大小(≤5MB)、同名覆盖策略
- 移动文件、生成缩略图(可选)
- 入库保存业务信息(标题、押金、招聘、地点、图片路径、简介等)
完整代码
<?php
session_start();
if (empty($_SESSION['Company'])) { exit; }
// 上传配置
$uptypes = ['image/jpg','image/jpeg','image/png','image/pjpeg','image/gif','image/bmp','application/x-shockwave-flash','image/x-png'];
$max_file_size = 5000000; // 5MB
$dateDir = date('Ymd');
$uploadDir = __DIR__ . "/$dateDir/";
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true); // 递归创建
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!is_uploaded_file($_FILES['Pic']['tmp_name'])) {
exit('文件不存在!');
}
$file = $_FILES['Pic'];
if ($file['size'] > $max_file_size) exit('文件太大!');
if (!in_array($file['type'], $uptypes)) exit('只能上传图像或Flash!');
$ext = pathinfo($file['name'], PATHINFO_EXTENSION);
$newName = time() . '.' . $ext;
$destPath = $uploadDir . $newName;
if (file_exists($destPath)) exit('同名文件已存在!');
if (!move_uploaded_file($file['tmp_name'], $destPath)) exit('上传出错!');
// 入库(示例使用自定义 Factory/BLL 模式)
require_once __DIR__ . '/../../Module/Factory.php';
$Factory = new Factory();
$BLL_Trade = $Factory->FactoryTrade();
try {
$Infor = new Infor();
$Infor->Title = $_POST['Title'];
$Infor->Deposit = $_POST['Deposit'];
$Infor->Hire = $_POST['Hire'];
$Infor->Location = $_POST['Location'];
$Infor->Pic = "$dateDir/$newName"; // 存相对路径
$Infor->Intro = $_POST['Intro'];
$Infor->Member->ID = $_SESSION['MemberId'] ?? '';
$Infor->Goods->BarCode = $_POST['GoodsBarCode'] ?? 0;
$Infor->Class->ID = 0;
$Infor->IssueTime = time();
$Infor->ViewNum = 0;
$Infor->State = 1;
$Infor->Top = 0;
$Infor->Recommend = 0;
$Infor->BookMember->ID = 0;
$Infor->BookTime = 0;
$Infor->BookRemark = 0;
$BLL_Trade->CreateInfor($Infor);
echo '发布信息成功!';
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
安全加固要点
- 类型双重校验:前端 `accept` + 后端 MIME + 扩展名白名单 +
getimagesize() 验证真实图片头。
- 文件名随机化:`time().rand().ext` 或 `uniqid()`,避免覆盖与遍历攻击。
- 目录权限:上传目录设置 **不可执行** (Nginx/Apache 配置 `location ~ \.php$ { deny all; }`)。
- 大小限制:PHP `upload_max_filesize` / `post_max_size` 与代码双重限制。
- 入库参数化:示例中 `Infor` 对象赋值后由 BLL 处理,底层应使用 PDO 预处理防注入。
缩略图生成(可选扩展)
if ($imgpreview) {
list($w, $h) = getimagesize($destPath);
$thumbW = $w * $imgpreviewsize;
$thumbH = $h * $imgpreviewsize;
$src = imagecreatefromjpeg($destPath); // 针对类型分支
$dst = imagecreatetruecolor($thumbW, $thumbH);
imagecopyresampled($dst, $src, 0,0,0,0, $thumbW,$thumbH, $w,$h);
imagejpeg($dst, $uploadDir . 'thumb_' . $newName);
imagedestroy($src); imagedestroy($dst);
}