php - 在 php api 上验证图像文件时出错
问题描述
我正在开发一个 api,它可以在上面获取图像并将其调整为三种尺寸并压缩它。我有一些方法来验证文件,运行 resizer 类及其方法,最后将文件作为 zip 文件和下载它们的链接。现在我遇到了内容类型验证和压缩的问题。我搜索了很多,我找不到任何教程。如果您帮助我解决我的错误,我将不胜感激。
休息.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);
}
}
解决方案
getimagesize不用于将文件验证为图像
$imgsize = getimagesize($sourceFile);
$srcWidth = $imgsize[0];
$srcHeight = $imgsize[1];
$mime = $imgsize['mime'];
你可以使用:文件信息
或者您可以使用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) {
}
检查更多文件大小
编辑:您可以检查此链接以使用 PHP 压缩文件
编辑:
$this->request = $_FILES + $_POST; // this is insecure way to get the data
检查 $_POST 数据清理 在 php 中清理整个 $_POST 数组的好方法是什么?