Created
January 17, 2018 16:44
-
-
Save nathanbarrett/f84d4287c3d88214f1727f8653582e1f to your computer and use it in GitHub Desktop.
Trait for guessing mime types and extensions of files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Traits; | |
| // composer require ralouphie/mimey | |
| use Mimey; | |
| trait GuessesMimeTypesAndExtentions | |
| { | |
| /** | |
| * Guesses the mime type of a file based off of the extension in the file name | |
| * @param string $filename | |
| * @return mixed | |
| */ | |
| protected function guessMimeTypeByExtension($filename) | |
| { | |
| if ( ! $filename) | |
| { | |
| return null; | |
| } | |
| $dotPos = strrpos($filename, '.'); | |
| if ( ! $dotPos) | |
| { | |
| return null; | |
| } | |
| $extention = substr($filename, $dotPos + 1); | |
| $mimey = new Mimey\MimeTypes; | |
| return $mimey->getMimeType($extention); | |
| } | |
| /** | |
| * Guesses the extension of a file based off of the mime type given | |
| * @param string $mimeType | |
| * @return mixed | |
| */ | |
| protected function guessExtensionByMimeType($mimeType) | |
| { | |
| if ( ! $mimeType) | |
| { | |
| return null; | |
| } | |
| $mimey = new Mimey\MimeTypes; | |
| return $mimey->getExtension($mimeType); | |
| } | |
| /** | |
| * Guesses the mime type of a file given the real path of the file in the system | |
| * @param string $filePath | |
| * @return mixed | |
| */ | |
| protected function guessMimeTypeByFilePath($filePath) | |
| { | |
| if ( ! $filePath) | |
| { | |
| return null; | |
| } | |
| $finfo = finfo_open(FILEINFO_MIME_TYPE); | |
| $mimeType = finfo_file($finfo, $filePath); | |
| finfo_close($finfo); | |
| return $mimeType; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment