Check if the file is a PNG image file by reading its signature

Here is a quick function to check if a file is a PNG file by reading the file's signature. As this page on Wikipedia states, "A PNG file starts with an 8-byte signature. The hexadecimal byte values are 89 50 4E 47 0D 0A 1A 0A; the decimal values are 137 80 78 71 13 10 26 10".

Knowing that we can compare the first 8 bytes of the file itself to this list. And here is how:

  1. <?php
  2.  
  3. /**
  4.  * Check if a file is a PNG file. Does not depend on the file's extension
  5.  *
  6.  * @param string $filename Full file path
  7.  * @return boolean|null
  8.  */
  9. function isPngFile($filename)
  10. {
  11.     // check if the file exists
  12.     if (!file_exists($filename)) {
  13.         return null;
  14.     }
  15.    
  16.     // define the array of first 8 png bytes
  17.     $png_header = array(137, 80, 78, 71, 13, 10, 26, 10);
  18.  
  19.     // open file for reading
  20.     $f = fopen($filename, 'r');
  21.  
  22.     // loop through first 8 bytes of the file
  23.     for ($i = 0; $i < 8; $i++) {
  24.         // convert current character to its ascii value
  25.         $byte = ord(fread($f, 1));
  26.  
  27.         // return false if it doesn't match png's header
  28.         if ($byte !== $png_header[$i]) {
  29.             fclose($f);
  30.             return false;
  31.         }
  32.     }
  33.     fclose($f);
  34.  
  35.     return true;
  36. }

Showing 1 - 1 of 1 results