首页 > 编程语言 >PHP文件上传封装

PHP文件上传封装

时间:2023-06-29 09:00:39浏览次数:42  
标签:uploaded 封装 ERR UPLOAD file return PHP 上传 allowedExtensions

class FileUploader {
    private $targetDirectory;
    private $allowedExtensions;
    private $maxFileSize;

    public function __construct($targetDirectory, $allowedExtensions = array(), $maxFileSize = 1048576) {
        $this->targetDirectory = $targetDirectory;
        $this->allowedExtensions = $allowedExtensions;
        $this->maxFileSize = $maxFileSize;
    }

    public function upload($fileInputName) {
        if (!isset($_FILES[$fileInputName])) {
            throw new Exception('File input not found.');
        }

        $file = $_FILES[$fileInputName];
        $filename = $file['name'];
        $fileTmpPath = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileError = $file['error'];

        // Validate file error
        if ($fileError !== UPLOAD_ERR_OK) {
            throw new Exception('File upload error: ' . $this->getFileErrorMessage($fileError));
        }

        // Validate file size
        if ($fileSize > $this->maxFileSize) {
            throw new Exception('File size exceeds the maximum limit.');
        }

        // Validate file extension
        $fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        if (!empty($this->allowedExtensions) && !in_array($fileExtension, $this->allowedExtensions)) {
            throw new Exception('Invalid file extension.');
        }

        // Generate unique filename
        $newFilename = uniqid() . '.' . $fileExtension;
        $destinationPath = $this->targetDirectory . '/' . $newFilename;

        // Move uploaded file to destination
        if (!move_uploaded_file($fileTmpPath, $destinationPath)) {
            throw new Exception('Failed to move uploaded file.');
        }

        return $newFilename;
    }

    private function getFileErrorMessage($errorCode) {
        switch ($errorCode) {
            case UPLOAD_ERR_INI_SIZE:
                return 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
            case UPLOAD_ERR_FORM_SIZE:
                return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
            case UPLOAD_ERR_PARTIAL:
                return 'The uploaded file was only partially uploaded.';
            case UPLOAD_ERR_NO_FILE:
                return 'No file was uploaded.';
            case UPLOAD_ERR_NO_TMP_DIR:
                return 'Missing a temporary folder.';
            case UPLOAD_ERR_CANT_WRITE:
                return 'Failed to write file to disk.';
            case UPLOAD_ERR_EXTENSION:
                return 'A PHP extension stopped the file upload.';
            default:
                return 'Unknown error occurred.';
        }
    }
}

使用示例:

$targetDirectory = '/path/to/uploads';
$allowedExtensions = array('jpg', 'png', 'gif');
$maxFileSize = 1048576; // 1MB

$fileUploader = new FileUploader($targetDirectory, $allowedExtensions, $maxFileSize);

try {
    $uploadedFilename = $fileUploader->upload('file_input_name');
    echo 'File uploaded successfully. Filename: ' . $uploadedFilename;
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

在上述示例中,FileUploader 类封装了文件上传的功能。你可以通过在实例化 FileUploader 类时指定目标目录、允许的文件扩展名和最大文件大小来进行配置。然后,调用 `upload

标签:uploaded,封装,ERR,UPLOAD,file,return,PHP,上传,allowedExtensions
From: https://www.cnblogs.com/zxingduo/p/17513104.html

相关文章

  • wifi智能计量插座-10A 定时上传插座状态,电压,电流有功功率,视在功率,功率因数电量,温度 至
    wifi智能计量插座-10A定时上传插座状态,电压,电流有功功率,视在功率,功率因数电量,温度至MQTT服务器wifi智能计量插座-10A定时上传wifi智能计量插座-10A定时上传插座状态,电压,电流有功功率,视在功率,功率因数电量,温度至MQTT服务器插座状态,电压,电流有功功率,视在功率,功率因数电量,温度......
  • php php截取指定两个字符之间字符串,默认字符集为utf-8
    /**php截取指定两个字符之间字符串,默认字符集为utf-8Powerby大耳朵图图@paramstring$begin开始字符串@paramstring$end结束字符串@paramstring$str需要截取的字符串@returnstring*/publicfunctioncut($begin,$end,$str){$b=mb_strpos($str,$begin)+mb......
  • php获取姓氏开头字母
    原文地址functiongetChineseInitials($chinese){$pinyin='';//多音字姓氏映射数组$multiPinyinMap=['单'=>['S','D'],'区'=>['O','Q'],'仇......
  • 字节抖音php解密留资的手机号
    订单查询(https://partner.open-douyin.com/docs/resource/zh-CN/local-life/develop/OpenAPI/order.query/query)接口返回的留资联系电话(加密提供)。加密字段解密方法(https://partner.open-douyin.com/docs/resource/zh-CN/local-life/develop/preparation/decrypt) /***......
  • 在element-ui视频上传使用canvas截取视频帧数,并且转为视频封面。
    <el-upload:http-request="getFile"//自定义上传action:on-change="handleFileChange"//监听文件上传ref="upload"accept="video/*"//定义格式为视频><el-butto......
  • webuploader http大文件断点续传上传
    ​ javaweb上传文件上传文件的jsp中的部分上传文件同样可以使用form表单向后端发请求,也可以使用ajax向后端发请求    1.通过form表单向后端发送请求         <formid="postForm"action="${pageContext.request.contextPath}/UploadServlet"method="post"e......
  • 自媒体后台搭建 —— 素材图片上传
    一、自媒体后台搭建1、搭建自媒体平台网关:leadnew-wemedia-gateway2、搭建自媒体微服务:leadnews-wemedia-service二、自媒体素材管理图片上传1、如何获得用户信息在自媒体网关过滤器filter中解析token,获取用户id,存入headerspackagecom.heima.wemedia.gateway.filter;......
  • csharp http大文件断点续传上传
    ​IE的自带下载功能中没有断点续传功能,要实现断点续传功能,需要用到HTTP协议中鲜为人知的几个响应头和请求头。 一. 两个必要响应头Accept-Ranges、ETag        客户端每次提交下载请求时,服务端都要添加这两个响应头,以保证客户端和服务端将此下载识别为可以断点续传......
  • php如何解决高并发
    PHP交流群  656679284  为PHP广大爱好者提供技术交流,有问必答,相互学习相互进步! 1、应用和静态资源分离将静态资源(js,css,图片等)放到专门的服务器中。 2、页面缓存将应用生成的页面缓存起来可以节省大量cpu资源。对于部分页面经常变换数据的,可以使用ajax来处理。 3、......
  • PHP根据身份证号码,获取性别、获取生日、计算年龄等多个信息
    /***根据身份证号码获取性别*@paramstring$idcard身份证号码*@returnint$sex性别1男2女0未知*/functionget_sex($idcard){if(empty($idcard))returnnull;$sexint=(int)substr($idcard,16,1);return$sexint%2===0?'女'......