samayo/bulletproof

一个简单且安全的PHP图像上传器

v5.0.2 2024-05-05 18:26 UTC

README

Latest Stable Version Total Downloads Scrutinizer Code Quality License

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() 检查图像是否有有效的像素高度/宽度。
  • 清理后的图像名称、严格的文件夹权限等...

许可证:MIT