简体   繁体   English

如何检查给定的字符串是否是 PHP 中的有效 base64 png/图像?

[英]How to check if given string is a valid base64 png/image in PHP?

The following code is intended to save a.png file in the disk from a base64 encoded image read from the POST sent by the user.以下代码旨在从用户发送的 POST 读取的 base64 编码图像中将 .png 文件保存在磁盘中。

$base64_string = $_POST["photo"];
$output_file = trim(getcwd()."/uploads/".uuid4().'.png');    
file_put_contents($output_file, file_get_contents($base64_string));

But it saves anything in the server disk, forcing a.png extension though.但它会在服务器磁盘中保存任何内容,尽管强制使用 .png 扩展名。

It seems very unsafe, how the POST string can be checked for a valid image to prevent the script from saving it?看起来很不安全,如何检查 POST 字符串中的有效图像以防止脚本保存它?

You can check first the filetype and proper way to upload base64 image by using the code blow;您可以先检查文件类型和上传 base64 图像的正确方法,使用代码打击;

    $fileImg_parts  = explode(";base64,", $_POST['photo']);
    $image_type_aux = explode("image/", $fileImg_parts[0]);
    $image_type     = $image_type_aux[1];
    $image_base64   = base64_decode($fileImg_parts[1]);
    $file_name      = uniqid() . '.'.$image_type;

    //You can add condition here to check image type using $image_type variable
    
    $results        = FILE_UPLOAD_DIR . $file_name;
    file_put_contents($results, $image_base64);

It will check type first and then put it into the direcoty.它将首先检查类型,然后将其放入目录中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM