【问题标题】:error on validating image file on php api在 php api 上验证图像文件时出错
【发布时间】:2021-11-11 17:41:02
【问题描述】:

我正在开发一个 api,它可以在上面获取图像并将其调整为三种尺寸并压缩它。我有一些方法来验证文件,运行 resizer 类及其方法,最后将文件作为 zip 文件和下载它们的链接。现在我遇到了内容类型验证和压缩的问题。我搜索了很多,我找不到任何教程。如果您能帮助我解决我的错误,我将不胜感激。

rest.php

<?php
require_once 'constants.php';

abstract class Rest
{
public array $request;
public array $errors = [];

public function __construct()
{
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        $this->throwError(REQUEST_METHODS_NOT_VALID, 'Request method is not valid.');
    }

    $this->request = $_FILES + $_POST;
    $fileName = $_FILES['image']['name'];
    $fileType = $_FILES['image']['type'];

    $this->validateRequest($fileName);
    if (empty($this->errors)){
        $this->executeApi();
    }
    $this->response();
}

public abstract function validateRequest($request);

public abstract function executeApi();

public function validateParameters($fieldName, $value, $dataType, $required) {

}

public function throwError($code, $message) {
    header("content-type: application/json");
    $errorMsg = json_encode(['error'=>['status'=>$code, 'message'=>$message]]);
    echo $errorMsg;
    exit();
}

public function response() {
 //???
}
}

api.php

<?php
 require_once 'image-resizer.php';
 class Api extends Rest
{

public function validateRequest($request)
{
  //        if ($request !== 'image/jpeg') {
    if ($_SERVER['CONTENT_TYPE'] !== 'image/jpeg') {
        $this->throwError(REQUEST_CONTENT_TYPE_NOT_VALID, 'Request content type is not valid.');
        $errors = json_encode(array("message" => "Request content type is not valid.", "status" => false));
        echo $errors;
    }
    json_decode($request, true);
}

public function executeApi()
{
    $source = $this->request['image'];
    $resize = new Resizer();
    $resize->imageResizer($source);

}
}

【问题讨论】:

    标签: php api


    【解决方案1】:

    getimagesize 不能用于将文件验证为图像

    $imgsize = getimagesize($sourceFile);
    $srcWidth = $imgsize[0];
    $srcHeight = $imgsize[1];
    $mime = $imgsize['mime'];
    

    您可以使用:fileinfo

    或者您可以使用pathinfo 验证扩展

    $allowedExt = ['jpg', 'jpeg', 'png'];
    $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExt)) {
          return FALSE;
    }
    
    // filesize validation
    if (filesize($tmpName) > MAX_FILE_SIZE) {
        
    }
    

    filesize上查看更多信息

    编辑: 您可以查看link 以使用 PHP 压缩文件

    编辑:

    $this->request = $_FILES + $_POST; // this is insecure way to get the data
    

    检查 $_POST 数据清理 what is a good method to sanitize the whole $_POST array in php?

    【讨论】:

    • 感谢您的回答。所以我在我的 validateRequest() 中添加了这个,对吧?
    • 是的,您可以在该方法中使用它,这取决于您的要求需要什么类型的验证,(如扩展验证等)
    • 我想验证整个请求,例如大小和类型
    • 添加文件大小验证,您可以检查类型的扩展名
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 2017-03-26
    • 2018-07-19
    • 2017-03-06
    • 2019-02-08
    • 2014-12-29
    • 2020-07-10
    相关资源
    最近更新 更多