Skip to content
Advertisement

How to get MIME-TYPE from Base 64 String of PPT or docx?

I am getting base64 string from append and I am then decoding it in PHP and saving it in the database.

This string can be any file .pdf, .img, .docx, .zip, .ppt, .docx etc.

My base64 string does not include the mime-type for example ‘data:application/pdf;base64’ part. So I need to get mime type of base64.

Is there any way to solve this solution with PHP?

Currently, I am using this code and it is working fine for Images and pdf.

$file = base64_decode($formData['image'], true)

$mineType = $this->getMimeType($file);

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

    return implode($bytes);
}

public function getMimeType($imagedata)
{
    $imagemimetypes = array(
        "jpg" => "FFD8",
        "png" => "89504E470D0A1A0A",
        "gif" => "474946",
        "bmp" => "424D",
        "tiff" => "4949",
        "pdf" => "25504446",
        "docx"=> "504B0304",
        "doc" => "D0CF11E0A1",
        "xlsx"=> "504B030414000600",
        "xls" => "D0CF11E0A1B11AE1"
    );

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

    return false;
}

Advertisement

Answer

function base64_mimetype(string $encoded, bool $strict = true): ?string {
    if ($decoded = base64_decode($encoded, $strict)) {
        $tmpFile = tmpFile();
        $tmpFilename = stream_get_meta_data($tmpFile)['uri'];

        file_put_contents($tmpFilename, $decoded);

        return mime_content_type($tmpFilename) ?: null;
    }

    return null;
}

http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement