老师好, 10月12日作业如下,自定义一个上传异常类,如果出现页面错误,不是因为远程服务器数据库里,没有相应的表引起的,而是因为数据库密码不同引起的。点击页面底部的php中文网图片可以返回我的博客页面,老师辛苦了,感恩感恩。 最近事很多,比较忙,而且由于纽约进入了冬令时,从而时差变为了13小时,以至于无法第一时间看直播了,但是还是会忙里偷闲看录播以及补写作业的,由于本次作业是图片上传,会对线上服务器造成压力,所以不再发布到线上服务器,全部采用代码和本地测试截图方式完成,多谢多谢,代码如下:
表单部分
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title></head> <body> <form action="form.php" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <button>上传</button> </form> </body> </html>
PHP部分
<?php
//use Exception;
class FileException extends Exception{
public function __construct($message = "",$code = 0) { parent::__construct($message,$code); }
public function errorInfo(){
return <<<ERROR
<h2>
<strong>{$this->getCode()}:</strong> <span style="color:red">{$this->getMessage()}</span> </h2>
ERROR; } }
try{
$filetype = ['jpg','jpeg','gif','png'];
$filesize = 4000000;
$filepath = '/uploads/';
if(isset($_FILES['file']['name'])){
$filename = $_FILES['file']['name'];
$tempname = $_FILES['file']['tmp_name']; }else{
$error = $_FILES['file']['error'];
if($error > 0){
switch($error){
case 1:
case 2: throw new FileException('文件超过3M',12);
case 3: throw new FileException('上传文件不完整',3);
case 4: throw new FileException('没有上传文件',4);
default: throw new FileException('未知错误',5); } } }
$extension = explode('.',$filename);
//echo $extension;
if(!in_array($extension,$filetype)){
throw new FileException('请上传图片文件',6);
}else{
echo '您上传的是 '.$extension.' 格式的图片。'; }
$filename = date('YmdHis'.time()).md5(mt_rand(1,99)).'.'.$extension;
//echo $filename;
if(is_uploaded_file($tempname)){
if(move_uploaded_file($tempname,__DIR__.$filepath.$filename)){
echo '<strong style="color:lightgreen">图片上传成功!</strong>'; }else{
echo '无法移动图片,请重试!'; }
}else{
echo '<strong style="color:red">上传错误</strong>'; }
}catch(FileException $e){ echo $e->errorInfo(); }
?>功能测试截图



Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号