我有一個接受base64編碼圖像數據的API,需要解碼數據,保存圖像文件,然後從該圖像創建縮略圖。使用base64編碼圖像的安全問題
我擔心如果在嘗試創建縮略圖之前未正確驗證POST有效內容的內容,惡意代碼可能會被執行。
我到目前爲止的基本工作流程如下。是否有足夠的驗證,我不需要關心安全性?我想我擔心某人編碼不好的東西,然後當下面的一個圖像函數被調用時,互聯網爆炸。
<?php
$decodedImage = base64_decode($_POST["canvas"]);
if ($decodedImage === false) {
// Error out
}
$imageSizeValidation = getimagesizefromstring($decodedImage);
if ($imageSizeValidation[0] < 1 || $imageSizeValidation[1] < 1 || !$imageSizeValidation['mime']) {
// Error out
}
$tempFilePath = "/tmp/" . microtime(true) . "-canvas-web.jpg";
file_put_contents($tempFilePath, $decodedImage);
$originalWidth = $imageSizeValidation[0];
$originalHeight = $imageSizeValidation[1];
$newWidth = 49;
$newHeight = 49;
$scaleWidth = $newWidth/$originalWidth;
$scaleHeight = $newHeight/$originalHeight;
$scale = min($scaleWidth, $scaleHeight);
$width = (int)($originalWidth * $scale);
$height = (int)($originalHeight * $scale);
$xpos = (int)(($newWidth - $width)/2);
$ypos = (int)(($newHeight - $height)/2);
$oldImage = imagecreatefromjpeg($tempFilePath);
$newImage = imagecreatetruecolor($width, $height);
$background = imagecolorallocate($oldImage, 255, 255, 255);
imagefilledrectangle($newImage, 0, 0, $width, $height, $background);
imagecopyresampled($newImage, $oldImage, $xpos, $ypos, 0, 0, $width, $height, $originalWidth, $originalHeight);
imagedestroy($oldImage);
imagejpeg($newImage, "/path/to/new.jpg", 90);
imagedestroy($newImage);