Mystical
Mystical

Reputation: 2773

Get the file extension of a base64 encoded string

How can you get the file extension of a base64 encoded string in PHP?

In my case, this file happens to be an image:

$base64_encoded_string = $_POST['image_base64_string'];

$extension = ??

How can I get the file extension from $base64_encoded_string ?

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

Upvotes: 19

Views: 33834

Answers (6)

Serhii Popov
Serhii Popov

Reputation: 3804

In my case, when I tried to upload a CSV file all examples returned the plain/text mime type, which technically is true but wrong when we try to find a file extension.

I ended up with the following solution (some Symfony code presented):

$base64Uri = "data:text/csv;base64,iVBORw0KGgoAAAANSUhEUgAAAF.......";
preg_match('/^data:(.*);base64/', $base64Uri, $match);
$mimeType = $match[1];
$extension = \Symfony\Component\Mime\MimeTypes::getDefault()->getExtensions($mimeType)[0];

Upvotes: 0

Regex can extract the image type from the base64 header :

                  ┌───┐
$b64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAIAQMAAAD+wSzIAAAABlBMVEX///+/v7+jQ3Y5AAAADklEQVQI12P4AIX8EAgALgAD/aNpbtEAAAAASUVORK5CYII";
preg_match("/\/(.*?);/", $b64, $MATCH);
              ↑     ↑
              └─────┘  RETURNS STRING BETWEEN / AND ;
echo $MATCH[1];

It should display png.

Notice the slash must be escaped \/, while semicolon does not require it.

Upvotes: 2

//This function return the extension from mimetype
function getImageMimeType(string $encodedImage)
{
    $decodedImage = base64_decode($encodedImage);
    return (explode('/', finfo_buffer(finfo_open(), $decodedImage, FILEINFO_MIME_TYPE))[1]);
}
    
$encodedImage = '        ';
$extension = getImageMimeType($encodedImage);
echo $extension;

Upvotes: 5

Elnur Ibrahim-zade
Elnur Ibrahim-zade

Reputation: 821

This worked for me

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);

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

Upvotes: 3

Mystical
Mystical

Reputation: 2773

Here is a one-liner inspired by @msg's answer:

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

Upvotes: 33

msg
msg

Reputation: 8161

If this is part of a upload form, you can get the information about the files from the $_FILES variable.

If it's a raw field you can decode it and run it through mime_content_type or equivalent and take a guess.

If you are open to using libraries, you can look into mimey or php-mimetyper.

Upvotes: 2

Related Questions