Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 922
Mystical Avatar asked Sep 23 '18 04:09

Mystical


2 Answers

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

$extension = explode('/', mime_content_type($base64_encoded_string))[1];
like image 164
Mystical Avatar answered Oct 31 '22 03:10

Mystical


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.

like image 40
msg Avatar answered Oct 31 '22 03:10

msg