CoderZone.org

Category: >> PHP Code >> More File Type Detection in PHP Bookmark and Share

<< lastnext >>

Snippet Name: More File Type Detection in PHP

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

Also see:
» Simple directory viewer / browser
» Read a web page directly in to a s...
» Recursive Directory Browser
» Get A Directory Listing Of Specifi...
» Easily detect Odd/Even numbers
» Saving Remote Images With PHP
» Include All Files In A Directory
» Get Current Page URL
» Get Current Directory Name
» Measure script run time
» TABLESPACE: Set default tablespace...
» Data Types
» %TYPE vs %ROWTYPE - What's the dif...
» Detect Leap Year
» Write to File example
» Check if a file exists
» Browser sniffer / detector
» Export table to Excel or MS Word f...
» Detect Daylight Saving Time
» Change table type
» Alias and RowType
» Detect Mobile/WAP browser
» Count lines in file
» Copy File From Server
» Remove All Files An A Given Direct...
» Calculate File/Folder Size In A Di...

Comment: (none)

Author: CoderZone
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.
      }
 }
 
 
There haven't been any comments added for this snippet yet. You may add one if you like.  Add a comment 
© coderzone.org | users online: 5