获取 base64 编码字符串的文件扩展名

Get the file extension of a base64 encoded string

如何在PHP中获取base64编码字符串的文件扩展名?

在我的例子中,这个文件恰好是 image:

$base64_encoded_string = $_POST['image_base64_string'];

$extension = ??

如何获取 $base64_encoded_string 的文件扩展名?

EDIT: This is NOT part of an upload form so $_FILES data cannot be used here.

如果这是上传表单的一部分,您可以从 $_FILES variable.

中获取有关文件的信息

如果它是原始字段,您可以对其进行解码,然后 运行 通过 mime_content_type 或等效方法对其进行解码,然后进行猜测。

如果您愿意使用库,可以查看 mimey or php-mimetyper

这是受 @msg 的 回答启发的单行代码:

$extension = explode('/', mime_content_type($base64_encoded_string))[1];

这对我有用

function getBytesFromHexString($hexdata)
{
  for($count = 0; $count < strlen($hexdata); $count+=2)
    $bytes[] = chr(hexdec(substr($hexdata, $count, 2)));

  return implode($bytes);
}

function getImageMimeType($imagedata)
{
  $imagemimetypes = array( 
    "jpeg" => "FFD8", 
    "png" => "89504E470D0A1A0A", 
    "gif" => "474946",
    "bmp" => "424D", 
    "tiff" => "4949",
    "tiff" => "4D4D"
  );

  foreach ($imagemimetypes as $mime => $hexbytes)
  {
    $bytes = getBytesFromHexString($hexbytes);
    if (substr($imagedata, 0, strlen($bytes)) == $bytes)
      return $mime;
  }

  return NULL;
}

$encoded_string = "....";
$imgdata = base64_decode($encoded_string);
$mimetype = getImageMimeType($imgdata);

来源:https://newbedev.com/detecting-image-type-from-base64-string-in-php