Quick Search:
 
 PHP Code: More File Type Detection in PHP Jump to:  
Category: >> PHP Code >> More File Type Detection in PHP  

<< lastnext >>

Snippet Name: More File Type Detection in PHP

Description: Detect files type in PHP. Not absolutely foolproof, but very good.

Also see:
» Easily detect Odd/Even numbers
» Saving Remote Images With PHP
» Include All Files In A Directory
» More File Type Detection in PHP
» Get Current Page URL
» Get Current Directory Name
» Measure script run time
» TABLESPACE: Set default tablespace type
» Data Types
» %TYPE vs %ROWTYPE: What's the differen...
» Detect Leap Year
» Write to File example
» Check if a file exists
» Browser sniffer/detector
» Export table to Excel or MS Word file
» Detect Daylight Saving Time
» Change table type
» Alias and RowType
» Detect Mobile/WAP browser
» Count lines in file
» Copy File From Server
» Truncate URLs for clean appearance.
» Calculate File Size In Directory

Comment: (none)

Language: PHP
Highlight Mode: PHP
Last Modified: May 27th, 2010

<?PHP
 
FUNCTION strhex($string)
 {
    $hex = "";
    $len = STRLEN($string);
 
    FOR($i = 0; $i < $len; ++$i)
     {
       $hex .= STR_PAD(DECHEX(ORD($string[$i])), 2, 0, STR_PAD_LEFT);
     }
    RETURN $hex;
 }
 
$data = FILE_GET_CONTENTS($filename);
 
IF(PREG_MATCH('/\.(jpg|jpeg|gif|png)/i', $filename, $matches))
 {
    $type = ($matches[1] === 'jpeg') ? 'jpg' : $matches[1];
 }
ELSE
 {
     // Get the first 12 bytes of the file
     $hdr  = strhex($data[0].$data[1].$data[2].$data[3].$data[4].$data[5].$data[6].$data[7].$data[8].$data[9].$data[10].$data[11]);
     ECHO $hdr;
 
     // Match header of the file (Google it).
     IF(PREG_MATCH('$/ffd8ffe0....4A46494600/i', $hdr))
      {
        // JPEG?
        $type = 'jpg';
      }
     ELSEIF(PREG_MATCH('$/89504e470D0a1a0a/i', $hdr))
      {
        // PNG?
        $type = 'png';
      }
     ELSEIF(PREG_MATCH('$/474946/i', $hdr))
      {
        // GIF?
        $type = 'gif';
      }
     ELSE
      {
         // Unknown image type.
      }
 }
 


 
   Home |    Search |    Code Library |    Sponsors |    Privacy |    Terms of Use |    Contact Us © 2003 - 2024 psoug.org