0
我正在使用CropIt JQuery插件來裁剪和上傳照片。選擇照片返回base64編碼圖像後的插件。就像這樣:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAA....
如何正確地將base64編碼圖像上傳到文件服務器?
我使用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()'檢查它是否是文件或類似的東西,也表示這是更安全的上傳方式。真的,我不知道這是真的。 – Infinity
您發送簡單的POST數據(使用data:url)。你不發送和文件,這就是爲什麼不能使用'move_uploaded_file()'。在這種情況下,您只能檢查數據類型(MIME,在此字符串中給出)並將解碼後的數據保存到文件中。當然,你也可以用給定的方式檢查保存圖像類型。 – Vitaly