方法一:
<?php
//图片上传与入库
include 'config.php';
try{
//非正常上传(恶意攻击)
if(!is_uploaded_file($_FILES['img']['tmp_name'])){
//抛出异常
throw new Exception('非正常上传');
}
//文件上传有误
if($_FILES['img']['error']!= 0){
throw new Exception('文件上传有误');
}
//文件最大2M
$maxsize = 2*1024*1024;
if($_FILES['img']['size']>$maxsize){
throw new Exception('文件最大2M');
}
//获取文件后缀
$srcname = $_FILES['img']['name'];
$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'];
$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);
if($smt->execute()){
//跳转到首页
header('location:index.php');
}
}
}catch (Exception $e){
//错误提示
echo $e->getMessage();
exit;
}
方法二:
假设上传的文件name值为upload
<form id="comment" action="{:url('supplement_order/index')}" method="post" enctype="multipart/form-data">
<input type="file" name="file_name" value="" >
<button class="submit" >提交</button>
</form>
服务端处理代码如下:
if(isset($_FILES['file_name']) && !$_FILES['file_name']['error']) {// 文件存在且不报错
$fileName = $_FILES['file_name']['name']; // 获取文件
$fileExtension = pathinfo($fileName); // 获取文件路径信息
$fileExtension = $fileExtension['extension']; // 获取文件后缀
$time = time(); // 根据时间戳区分
$destinationPath = "./upload/supplement_order/xlsx_ledge/"; // 目标文件夹
$newFileName = $destinationPath.$time.".".$fileExtension;
// 完整的url
if(rename($_FILES['file_name']['tmp_name'], $newFileName)) { // 移动文件到目标路径
echo("文件移动成功");
} else {
die("文件路径出错");
}
}
参考文档:
https://www.cnblogs.com/sysuzjz/p/4289309.html