Code:
<?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();
}
Comment