What are some best practices for identifying file types in a directory without uploading them?

When working with a directory containing various files, it can be useful to identify the file types without uploading them to a server. One way to achieve this is by using PHP to read the file headers and determine the file type based on the magic number or signature. This can be done by opening each file in the directory, reading the first few bytes, and matching them against known file signatures.

$directory = "/path/to/directory";

$files = scandir($directory);

foreach($files as $file) {
    if(is_file($directory . "/" . $file)) {
        $handle = fopen($directory . "/" . $file, "r");
        $bytes = fread($handle, 4); // Read the first 4 bytes
        fclose($handle);

        // Check file signature to determine file type
        if($bytes == "\x89PNG") {
            echo $file . " is a PNG file\n";
        } elseif($bytes == "GIF8") {
            echo $file . " is a GIF file\n";
        } elseif($bytes == "BM") {
            echo $file . " is a BMP file\n";
        } else {
            echo $file . " is an unknown file type\n";
        }
    }
}