Here is a working example using test files. Substitute $content
from $content = file_get_contents()
in your example. You can find signatures for other file types here. I chose to convert the first 12 characters to hex of each file. If you have file signatures that are longer, you can increase that number. For file size, you can use strlen($content)
or try filesize("php://input")
<?php
$content = file_get_contents("testjpg.jpg");
$a = strToHex($content, 12);
var_dump($a);
echo getfiletype($a) . "<br>";
$content = file_get_contents("testdoc.doc");
$a = strToHex($content, 12);
var_dump($a);
echo getfiletype($a) . "<br>";
$content = file_get_contents("testpdf.pdf");
$a = strToHex($content, 12);
var_dump($a);
echo getfiletype($a) . "<br>";
function getfiletype($test){
if (testsig($test, "FF D8 FF")){
return "jpeg";
}
elseif (testsig($test, "25 50 44 46")){
return "pdf";
}
elseif (testsig($test, "D0 CF 11 E0 A1 B1 1A E1")){
return "doc";
}
else{
return "unknown";
}
}
function testsig($test, $sig){
// remove spaces in sig
$sig = str_replace(" ","", $sig);
if (substr($test, 0, strlen($sig)) == $sig){
return true;
}
return false;
}
function strToHex($string, $stop=null){
$hex = "";
if ($stop == null){
$stop = strlen($string);
}
$stop = min(strlen($string), $stop);
for ($i=0; $i<$stop; $i++){
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0'.$hexCode, -2);
}
return strtoupper($hex);
}
?>
The result of the code is:
string 'FFD8FFE1034D457869660000' (length=24)
jpeg
string 'D0CF11E0A1B11AE100000000' (length=24)
doc
string '255044462D312E360D25E2E3' (length=24)
pdf