Check file signature in PHP

Posted on April 10, 2014 at 10:07 am

Use this function to get the file signature:

function get_file_type_signature( $str )
{
    $hex_ary = array();
    foreach( str_split( $str ) as $chr ) 
	{
        $hex_ary[] = sprintf("%02X", ord($chr));
    }
	$s = '';
    if ( $hex_ary ) foreach( $hex_ary as $item )
    {
       $s .= '\x'.$item;
    }
	return $s;
}

Generate the signature for specific file types:

echo "EXE: ".get_file_type_signature( "MZ" )
echo "PDF: ".get_file_type_signature( "PDF" )
echo "JAR: ".get_file_type_signature( "PK" )
echo "PNG: ".get_file_type_signature( "‰PNG...." )

Check if a file is a valid PE (EXE) file:

function isValidExe( $file )
{
    if ( !file_exists( $file ) ) return false;
    if ( $f = fopen($file, 'rb') ) 
	{
        $header = fread($f, 2);
        fclose($f);
	// Signature = MZ
        return strncmp($header, "\x4d\x5a", 2)==0 && strlen ($header)==2;
    }
    return false;
}

Check if a file is a valid PDF file:

function isValidPDF( $file )
{
    if ( !file_exists( $file ) ) return false;
 
    if ( $f = fopen($file, 'rb') ) 
	{
        $header1 = fread($f, 3);
	fclose($f);
	// Signature = PDF
        $check1 = strncmp($header1, "\x50\x44\x46", 3)==0 && strlen ($header1)==3;
    }
 
    if ( $f = fopen($file, 'rb') ) 
	{
        $header2 = fread($f, 4);
	fclose($f);
	// Signature = %PDF
        $check2 = strncmp($header2, "\x25\x50\x44\x46", 4)==0 && strlen ($header2)==4;
    }
 
    return ($check1 || $check2) ? true : false;
}

Check if a file is a valid Java JAR file:

function isValidJAR( $file )
{
    if ( !file_exists( $file ) ) return false;
    if ( $f = fopen($file, 'rb') ) 
	{
        $header = fread($f, 2);
        fclose($f);
	// Signature = PK
        return strncmp($header, "\x50\x4B", 2)==0 && strlen ($header)==2;
    }
    return false;
}

Check if a file is a valid PNG image file:

function isValidPNG( $file )
{
    if ( !file_exists( $file ) ) return false;
    if ( $f = fopen($file, 'rb') ) 
	{
        $header = fread($f, 8);
        fclose($f);
	// Signature = ‰PNG....
        return strncmp($header, "\x89\x50\x4e\x47\x0d\x0a\x1a\x0a", 8)==0 && strlen ($header)==8;
    }
    return false;
}

More information:

Table of file signatures (aka “magic numbers”)

Updated on November 9, 2017 at 1:49 pm

Receive updates via email

Other Posts

Updated Posts