samayo / bulletproof
一个简单且安全的PHP图像上传器
v5.0.2
2024-05-05 18:26 UTC
Requires
- php: >=8.1.0
- ext-exif: *
Requires (Dev)
- phpunit/phpunit: ^8
README
Bulletproof 是一个用于安全上传图像的单类 PHP 库。
安装
使用 git 安装
$ git clone https://github.com/samayo/bulletproof.git
使用 Composer 安装
$ composer require samayo/bulletproof:5.0.*
或者 手动下载ZIP格式
使用方法
要快速上传图像,请使用以下 HTML & PHP 代码
<form method="POST" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"/> <input type="file" name="pictures" accept="image/*"/> <input type="submit" value="upload"/> </form>
require_once "path/to/bulletproof.php"; $image = new Bulletproof\Image($_FILES); if($image["pictures"]){ $upload = $image->upload(); if($upload){ echo $upload->getPath(); // uploads/cat.gif }else{ echo $image->getError(); } }
有关更多选项或配置,请查看以下示例
配置
设置属性
设置图像名称、大小、类型等上传限制的方法
// To provide a name for the image. If unused, image name will be auto-generated. $image->setName($name); // To set the min/max image size to upload (in bytes) $image->setSize($min, $max); // To define a list of allowed image types to upload $image->setMime(array('jpeg', 'gif')); // To set the max image height/width to upload (limit in pixels) $image->setDimension($width, $height); // To create a folder name to store the uploaded image, with optional chmod permission $image->setStorage($folderName, $optionalPermission);
获取属性
在上传前后检索图像数据的方法。
// To get the image name $image->getName(); // To get the image size (in bytes) $image->getSize(); // To get the image mime (extension) $image->getMime(); // To get the image width in pixels $image->getWidth(); // To get the image height in pixels $image->getHeight(); // To get image location (folder where images are uploaded) $image->getStorage(); // To get the full image path. ex 'images/logo.jpg' $image->getPath(); // To get the json format value of all the above information $image->getJson();
扩展配置使用
如何使用属性设置器和获取器。
$image = new Bulletproof\Image($_FILES); $image->setName("samayo") ->setMime(["gif"]) ->setStorage(__DIR__ . "/avatars"); if($image["pictures"]){ if($image->upload()){ echo $image->getName(); // samayo echo $image->getMime(); // gif echo $image->getStorage(); // avatars echo $image->getPath(); // avatars/samayo.gif } }
图像处理
要裁剪、调整大小或水印图像,请使用存储在 src/utils
的函数
创建自定义错误
使用 php 异常来定义自定义错误响应
if($image['pictures']){ try { if($image->getMime() !== 'png'){ throw new \Exception('Only PNG image types are allowed'); } // check size, width, height... if(!$image->upload()){ throw new \Exception($image->getError()); } else { echo $image->getPath(); } } catch (\Exception $e){ echo "Error " . $e->getMessage(); } }
这为什么是安全的?
- 使用
exif_imagetype()
获取真实的图像 MIME 类型 (.extension
) - 使用
getimagesize()
检查图像是否有有效的像素宽度和高度。 - 清洗过的图像名称、严格的文件夹权限等...