hotti: FileType (Eigenbau)

Beitrag lesen

hi,

unten der Code. Bei mp3 ohne ID3 Tag bin ich mir nicht ganz sicher, ob das hex pattern fffb oder fffa lautet, wer Lust hat, teste mal ... danke!!

  
<?php  
  
  
// Die Klasse ist leicht erweiterbar:  
// Methode definieren und in $TYPES eintragen, fertig  
class FileType{  
	// Associate type => methods  
	// Möglicherweise gibt es mehrere Funktionen zum Prüfen eines Types  
	private $TYPES = array(  
		'image/gif'          => array('gif'),  
		'image/x-bmp'        => array('bmp'),  
		'application/pdf'    => array('pdf'),  
		'image/x-png'        => array('png'),  
		'image/jpeg'         => array('jpeg'),  
		'application/msword' => array('word97'),  
		'audio/mp3'          => array('id3', 'fffb'),  
		'application/zip'    => array('zip'),  
		'application/x-gzip' => array('gzip'),  
	);  
  
	/* ~~~~~~~~~~~~~~~~~ associated callback methods ~~~~~~~~~~~~~~~~ */  
	private function gzip($type){  
		if(fread($this->FH,2) == pack("H*", '1f8b')) return $type;  
	}  
	private function zip($type){  
		if('PK' != fread($this->FH,2)) return;  
		$s = fread($this->FH,2);  
		if($s == pack("H*", '0304')) return $type;  
	}  
	private function fffb($type){  
		if(fread($this->FH,2) == pack("H*", 'fffb')) return $type;  
	}  
  
	private function id3($type){  
		if(fread($this->FH,3) == 'ID3') return $type;  
	}  
	private function word97($type){  
		if(pack("H*", 'D0Cf11E0A1B11AE10000') == fread($this->FH, 10)){  
			return $type;  
		}  
	}  
	private function jpeg($type){  
		if(fread($this->FH,2) == pack("H*", 'ffd8')) return $type;  
	}  
  
	private function png($type){  
		fseek($this->FH,1,0);  
		if(fread($this->FH,3) == 'PNG') return $type;  
	}  
  
	private function bmp($type){  
		if(fread($this->FH,2) == 'BM') return $type;  
	}  
  
	private function gif($type){  
		if(fread($this->FH,4) == 'GIF8') return $type;  
	}  
  
	private function pdf($type){  
		if(fread($this->FH,5) == '%PDF-') return $type;  
	}  
  
	/* ~~~~~~~~~~~~~~~~~ associated callback methods ~~~~~~~~~~~~~~~~ */  
  
	function __construct($file){  
		// Handle erstellen  
		if(! $this->FH = fopen($file, "r")){  
			throw new Exception("IO-Error: Unable to open File '$file'");  
		}  
	}  
  
	public function type(){  
		$default_type = 'application/octet-stream';  
		foreach($this->TYPES as $type => $methods){  
			// call associated methods  
			foreach($methods as $callback_method){  
				if(! method_exists($this, $callback_method)) return $default_type;  
				fseek($this->FH, 0, 0);  
				if($return_type = $this->$callback_method($type)){  
					return $return_type;  
				}  
			}  
		}  
		return $default_type;  
	}  
} // End class FileType  
  
try{  
	$ft = new FileType('d:/tmp/x.mp');  
	echo $ft->type();  
}  
catch(Exception $e){  
	echo $e->getMessage();  
}  
  
  
return;  
?>