Search code examples
phpfile-uploadfaviconico

How to detect if a file is a favicon in PHP?


I need to check if an uploaded file is a favicon type and I need do it in a secure way.

If I upload a favicon file through an input file and print the $_FILES variable, I can see that the variable has the following type value:

image/vnd.microsoft.icon

I know that I can check if that value matches that, but I think that the user can dumper it. If someone could give me some tip I'd be grateful


Solution

  • If you want avoid using any external tools, https://github.com/lordelph/icofileloader provides a native PHP method for parsing .ico files

    $loader = new Elphin\IcoFileLoader\IcoFileService;
    try {
        /** @var Elphin\IcoFileLoader\Icon $icon */
        $icon = $loader->fromFile('/path/to/icon.ico');
    
        //perform further inspection or render the icon as an image here...
    
    } catch (\Exception $e) {
        //not an .ico file
    }