<input type="file" name="img[]" multiple>
<?php
//图片上传与入库
include 'config.php';
try{
foreach($_FILES['img']['error'] as $key=>$err){
//非正常上传(恶意攻击)
if(!is_uploaded_file($_FILES['img']['tmp_name'][$key])){
//抛出异常
throw new Exception('非正常上传');
}
//文件上传有误
if($_FILES['img']['error'][$key]!= 0){
throw new Exception('文件上传有误');
}
//文件最大2M
$maxsize = 2*1024*1024;
if($_FILES['img']['size'][$key]>$maxsize){
throw new Exception('文件最大2M');
}
//获取文件后缀
$srcname = $_FILES['img']['name'][$key];
$ext = array_pop(explode('.',$srcname));
//文件类型为png、jpg、gif
$types = ['png','jpg','gif'];
if(!in_array($ext,$types)){
throw new Exception('文件类型必须为png、jpg和gif');
}
//源文件和目标文件
$srcfile = $_FILES['img']['tmp_name'][$key];
$dstname = time().mt_rand().'.'.$ext;
$dstfile = 'public/uploads/'.$dstname;
//文件移动
if(move_uploaded_file($srcfile,$dstfile)){
//数据入库
$sql = "insert into yzm_img(name) values('{$dstname}')";
$smt = $pdo->prepare($sql);
$smt->execute();
}
}
//跳转到首页
header('location:index.php');
}catch (Exception $e){
//错误提示
echo $e->getMessage();
exit;
}