Skip to content

Instantly share code, notes, and snippets.

@mylk
Created August 15, 2016 08:49
Show Gist options
  • Save mylk/127329f928529a7a36d1c0af57e63c25 to your computer and use it in GitHub Desktop.
Save mylk/127329f928529a7a36d1c0af57e63c25 to your computer and use it in GitHub Desktop.
A class that guesses the file extension either from raw binary or base64 data
<?php
namespace Acme\AcmeBundle\Service;
class FileExtensionGuesserService
{
/**
* Guesses the mime type of a file by raw binary or base64 encoded content
* and returns its file type.
*
* @param binary | string $rawData
* @return string | null
*/
public function guessFromRaw($rawData)
{
// checks is raw data is base64 encoded and decodes to be raw binary
$isBase64 = \base64_encode(\base64_decode($rawData, true) === $rawData);
if ($isBase64) {
$rawData = \base64_decode($rawData);
}
// guess the mime type
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->buffer($rawData);
return $this->getExtensionFromMimeType($mimeType);
}
/**
* Returns the extension by mime type name.
*
* @param string $mimeType
* @return string | null
*/
private function getExtensionFromMimeType($mimeType)
{
$mimeTypesExtensionsMap = array(
"image/jpeg" => "jpg",
"image/pjpeg" => "jpg",
"image/png" => "png",
"image/x-png" => "png",
"image/gif" => "gif",
"image/svg+xml" => "svg",
"application/xml" => "svg",
"text/xml" => "svg",
"image/bmp" => "bmp",
"image/x-bmp" => "bmp",
"image/x-bitmap" => "bmp",
"image/x-xbitmap" => "bmp",
"image/x-win-bitmap" => "bmp",
"image/x-windows-bmp" => "bmp",
"image/ms-bmp" => "bmp",
"image/x-ms-bmp" => "bmp",
"application/bmp" => "bmp",
"application/x-bmp" => "bmp",
"application/x-win-bitmap" => "bmp"
);
if (isset($mimeTypesExtensionsMap, $mimeType)) {
return $mimeTypesExtensionsMap[$mimeType];
} else {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment