@@ -41,6 +41,9 @@ final class FileUpload
4141 /** @var string|false|null */
4242 private $ type ;
4343
44+ /** @var string|false|null */
45+ private $ extension ;
46+
4447 /** @var int */
4548 private $ size ;
4649
@@ -98,9 +101,9 @@ public function getSanitizedName(): string
98101 $ name = str_replace (['-. ' , '.- ' ], '. ' , $ name );
99102 $ name = trim ($ name , '.- ' );
100103 $ name = $ name === '' ? 'unknown ' : $ name ;
101- if ($ this ->isImage ()) {
104+ if ($ ext = $ this ->getSuggestedExtension ()) {
102105 $ name = preg_replace ('#\.[^.]+$#D ' , '' , $ name );
103- $ name .= '. ' . ( $ this -> getImageFileExtension () ?? ' unknown ' ) ;
106+ $ name .= '. ' . $ ext ;
104107 }
105108
106109 return $ name ;
@@ -134,6 +137,27 @@ public function getContentType(): ?string
134137 }
135138
136139
140+ /**
141+ * Returns the appropriate file extension (without the period) corresponding to the detected MIME type. Requires the PHP extension fileinfo.
142+ */
143+ public function getSuggestedExtension (): ?string
144+ {
145+ if ($ this ->isOk () && $ this ->extension === null ) {
146+ $ exts = finfo_file (finfo_open (FILEINFO_EXTENSION ), $ this ->tmpName );
147+ if ($ exts && $ exts !== '??? ' ) {
148+ return $ this ->extension = preg_replace ('~[/,].*~ ' , '' , $ exts );
149+ }
150+ [, , $ type ] = @getimagesize ($ this ->tmpName ); // @ - files smaller than 12 bytes causes read error
151+ if ($ type ) {
152+ return $ this ->extension = image_type_to_extension ($ type , false );
153+ }
154+ $ this ->extension = false ;
155+ }
156+
157+ return $ this ->extension ?: null ;
158+ }
159+
160+
137161 /**
138162 * Returns the size of the uploaded file in bytes.
139163 */
@@ -252,12 +276,11 @@ public function getImageSize(): ?array
252276
253277 /**
254278 * Returns image file extension based on detected content type (without dot).
279+ * @deprecated use getSuggestedExtension()
255280 */
256281 public function getImageFileExtension (): ?string
257282 {
258- return $ this ->isImage ()
259- ? explode ('/ ' , $ this ->getContentType ())[1 ]
260- : null ;
283+ return $ this ->getSuggestedExtension ();
261284 }
262285
263286
0 commit comments