我在我的网站上制作了一项功能,即用户通过从文件加载或使用其计算机的内置网络摄像头上传图像。
我理解我使用的验证方法:
还有安全,"服务器友好型" 以及可靠验证base64的方法?
(我在其他帖子中找不到任何有希望的方法。)
当我在某些地方面对相机时失败(以某种方式,base64受某些图片影响)
非常感谢您的帮助! - dragonfire
upload.php脚本:
<?php
$uploaded_file_b64 = htmlspecialchars($_POST['b64_img_url']); // string containing base64 of uploaded image
$FileName = "the_unique_uploaded_file_name.png";
$file_path = "/uploads/" . $FileName;
$file_relative_path = "../uploads/" . $FileName; // BUG: need to use relative path rather than absolute since absolute path doesn't work. Why???
//Must get actual base64 out of string by splicing it
$uploaded_file_actual_b64 = explode("base64,",$uploaded_file_b64);
//We need to get the second value from the array returned from explode() since there are two commas before the actual base64
$uploaded_file_actual_b64 = $uploaded_file_actual_b64[1];
// First try to decode then re-encode the base64. If works then perfect!
if ($uploaded_file_actual_b64 == base64_encode(base64_decode($uploaded_file_actual_b64))) {
// It worked!
echo "Valid base64!";
}
else {
// It failed! THIS IS WHERE IT ALWAYS ERRORS!! WHY???
echo "Not base64!";
}
// Try creating an image from the base64. If works then perfect!
$is_image = imagecreatefromstring(base64_decode($uploaded_file_actual_b64));
//doing this will help confirm it's an image, but it is still possible to inject php or js into
//the body of the image, but as long as we don't execute the image on the server
//then we should be fine
if ($is_image != false) {
echo "Valid image!";
} else {
echo "Not an image!";
}
// If we get up to here, then nothing has been tampered with!
echo "Secure!";
// Store the image on the server
if (file_put_contents($file_relative_path, base64_decode($uploaded_file_actual_b64))) {
echo "Upload success!";
} else {
echo "Upload failed!";
}
?>
客户端代码:
<form method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" id="b64_img_url" name="b64_img_url" style="display: none;"/>
<input type="submit" class="btn btn-success" value="Submit" />
<div id="btn_cam_capture" onclick="capture_webcam();">Capture</div>
<canvas id="camera-stream-canvas"></canvas>
<img id="img-drop-preview"/>
<script>
var canvas = document.getElementById("camera-stream-canvas");
function capture_webcam() {
// Executed when user takes shot.
// Previews the image by converting the canvas to a base64 image.
document.getElementById("img-drop-preview").src = canvas.toDataURL();
// The input which stores the base64
document.getElementById("b64_img_url").value = canvas.toDataURL();
}
</script>
</form>