您现在的位置是: 网站首页> PHP PHP
PHP图片上传
杨二桃
2021-05-18
【PHP】
1459人已围观
简介走过路过不要错过,完整的PHP图片上传代码在这里。
upload.html
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">文件名:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="提交">
</form>
html文件form表单上传文件必须以 post 方式且需要着重加 enctype="multipart/form-data"
upload.php
<?php
if ($_FILES["file"]["error"]>0) return "错误:".$_FILES["file"]["error"];
$allowedExts = array("gif", "jpeg", "jpg", "png");//设置格式
$allowedType = array("image/gif", "image/jpeg", "image/jpg", "image/pjpeg","image/x-png","image/png");//设置类型
$maxSize = 3145728;//设置文件大小
$savePath = './Uploads/Dataexcel/pushimg/';//设置文件上传目录
$newPath = time();//设置文件命名规则
/*============================分割线================================*/
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp); // 获取文件后缀名
//验证文件格式
if (!in_array($extension, $allowedExts) && in_array($_FILES["file"]["type"], $allowedType)) return "文件格式错误!";
//判断文件大小
if ($_FILES["file"]["size"] > $maxSize) return "文件过大!";
mkdir($savePath, 0777);//创建文件上传目录
rename($_FILES["file"]["name"],$newPath.'.'.$extension);//重命名
// 将文件上传到 ./Uploads/Dataexcel/pushimg/ 目录下
$fileup = move_uploaded_file($_FILES["file"]["tmp_name"], $savePath . $newPath.'.'.$extension);
if ($fileup != true) return "文件上传失败!";
//成功返回文件信息
return array(
'name'=>$_FILES["file"]["name"],
'type'=>$_FILES["file"]["type"],
'size'=>$_FILES["file"]["size"],
'extension'=>$extension,
'savepath'=>$savePath,
'savename'=>$newPath.'.'.$extension,
);