【发布时间】:2017-06-15 07:43:20
【问题描述】:
我正在使用CropIt JQuery 插件来裁剪和上传照片。选择照片返回 base64 编码图像后的插件。像这样:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA....
我正在使用 Ajax 将其发送到 PHP,如下所示:
$.ajax({
type: 'post',
url: 'upload.php',
data: $('form').serialize(),
success: function (data) {
$('.image-editor').cropit('imageSrc', 'images/' + data );
$('#change').css("background-image", "url('images/" + data + "')");
modal.style.display = "none";
}
});
如何通过 PHP 正确验证图像并将其存储到文件服务器?
目前我正在使用这样的 PHP 并且它正在工作,但是正如我之前所读到的,这种方法不安全并且没有任何验证:
function decode ($code) {
list($type, $code) = explode(';', $code);
list(, $code) = explode(',', $code);
$code = base64_decode($code);
file_put_contents('images/filename.jpg', $code); // there filename static for example
}
$testdata = $_POST["image-data"];
decode($testdata);
echo "filename.jpg";
我应该使用move_uploaded_file() 而不是file_put_contents() 吗?但是我怎么能用base64编码的图像来实现呢?
我看到了像这样验证文件的方法,但我不知道如何将它与 base64 编码的图像一起使用:
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 100000)
&& in_array($extension, $allowedExts)){
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else {
$fileName = $temp[0].".".$temp[1];
$temp[0] = rand(0, 3000); //Set to random number
$fileName;
if (file_exists("../img/imageDirectory/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
echo "Stored in: " . "../img/imageDirectory/" . $_FILES["file"]["name"];
}
}
}
else {
echo "Invalid file";
}
【问题讨论】:
-
你关心什么样的安全?
-
@OliverCharlesworth 我读过类似的 SO 问题并看到评论说最好使用
move_uploaded_file()而不是file_put_contents(),因为move_uploaded_file()检查它是否是文件或类似的东西,也说这是更安全的上传方式。真的,不知道是不是真的。 -
您发送简单的 POST 数据(带有 data:url)。你不发送和文件,这就是为什么不能使用
move_uploaded_file()。在这种情况下,您只能检查数据类型(mime,在此字符串中给出)并将解码的数据保存到文件中。当然,您也可以使用给定的方式检查保存图像类型。 -
@Vitaly 您能否提供一个使用
file_put_contents()进行验证的示例? -
将解码后的数据保存到临时文件并调用
getimagesize(php.net/manual/en/function.getimagesize.php)。比较哑剧。此外,您可以检查函数getimagesize(失败时为 FALSE)和base64_decode(失败时为 FALSE)的返回值。通过验证后,您可以将该文件移动到存储目录。
标签: javascript php jquery validation encoding