validate file extension by hex signature

Started on the old forum in November 2012 · view the original in the archive · old links redirect here

1 reply · 1,760 views · started 14 years ago · 1 min read

shushant Developer · 207 posts #1
<?php
// developed by shushant
//version v0.2

class HexSig {

 public $type = array(
             'png' => '89504e47',
             'jpg'  => 'ffd8',
             'gif'   => '47494638',
      );

 public function merge(array $array) {
        if (!empty ($array)) {
           $this->type = array_merge ($this->type, $array);
      }
   }

 public function validate($file, $callback = 0, $len = 10){

     $fh = fopen($file,'rb');
         if(!$fh) {
           throw new HexSig_Exception('Error unable to open file');
         }
         $char = fread($fh,$len);

      if (!$char){
           throw new HexSig_Exception('Unable to read file');
   }
         fclose($fh);

    $unpack = unpack('N',$char);

    $hex = dechex($unpack[1]); // convert decimal to hex

      foreach($this->type as $k => $v) {

     $val = substr($hex,0,strlen($v));

       if($val == $v) {

          if(!$callback == 0) call_user_func($callback);
               return true;
               break;
                    }
   }
                  throw new HexSig_Exception('Invalid File type');
     }
   }

class HexSig_Exception extends Exception {}

//sample
try {
$hexsig = new HexSig;
//Get the List of registrated file signature from http://en.m.wikipedia.org/wiki/List_of_file_signatures

//add more hex signature
//make sure apk is just a zip file nothing else

$hexsig->merge (array ('zip' => '504b0304','apk' => '504b0304'));
// if PHP >= 5.3
$hexsig->validate ('http://licensing.symbian.org/_/rsrc/1297769375009/home/symbian_foundation_logo.jpg',function() use ($hexSig){
echo 'this is an valid file';

});
//PHP <= 5.3
function cb(){
echo 'this is an valid file';

}
$hexsig->validate ('http://licensing.symbian.org/_/rsrc/1297769375009/home/symbian_foundation_logo.jpg',cb);
  }  catch (HexSig_Exception $err){
      echo $err->getMessage();
 }

demo PHP code - 71 lines - codepad

shushant Developer · 207 posts #2

updated now supports callback

Write your reply now; next you create a free account (or sign in) and it is posted right away. Sign in to reply.

Similar topics

Keyboard shortcuts

g f
Go to forums
g h
Go to your feed
g m
Go to messages
r
Reply (in a topic)
/
Search
j
Next post
k
Previous post
?
This list
Ctrl/⌘ + Enter
Send what you are writing
Ctrl/⌘ + B / I
Bold / italic while writing
Esc
Close