I'm developing an api on which it gets an image and resizes it into three sizes and zips it. I have some methods to validate the file, run the resizer class and its methods and finally give files as zip file and a link to download them. Now I have problem with content type validation and zipping. I searched a lot and I couldn't find any tutorial. I'd be thankful if you help me with my errors.
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);
}
}
CodePudding user response:
getimagesize is not to be used to validate a file as image
$imgsize = getimagesize($sourceFile);
$srcWidth = $imgsize[0];
$srcHeight = $imgsize[1];
$mime = $imgsize['mime'];
you can use: fileinfo
OR you may validate extension using 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) {
}
check more on filesize
Edit: You may check this link for zipping files with PHP
EDIT:
$this->request = $_FILES $_POST; // this is insecure way to get the data
check $_POST data sanitization what is a good method to sanitize the whole $_POST array in php?