PHP created JSON file has application mime type / octet-stream

I have a script that generates a JSON file from data. I have a second script that reads files from a directory in order to take only JSON and paste them into the database.

The problem is that the second script detects the MIME type "application / octet-stream" from my generated files instead application/json

I do not want to allow the application/octet-streamMIME type , since it can be anything (for security reasons: the second script loads the entire jsonfile into a directory (not just generated ones)).

Is there anyway to "set" the MIME type for the file?

Code that generates the file:

if($r_handle = fopen($s_file_name, 'w+')){
    fwrite($r_handle, json_encode($o_datas, JSON_HEX_QUOT | JSON_HEX_TAG));
    fclose($r_handle);
    return;
}

Code that reads JSON files:

$o_finfo = finfo_open(FILEINFO_MIME_TYPE);
$a_mimes =& get_mimes();
if(is_dir($s_dir) && $r_handle = opendir($s_dir)){
    while($s_file = readdir($r_handle)){
        $s_file_path = $s_dir.$s_file;
        $s_mime      = finfo_file($o_finfo, $s_file_path);
        if(!in_array($s_file, array('.', '..')) && in_array($s_mime, $a_mimes['json'])){
            // Some code
        }
    }
}
+4
1

fileinfo ( , file Unix) , ( "" ). , PHP- , , , , . Apache C:\Apache24\conf.magic, JPEG:

# JPEG images
0   beshort     0xffd8      image/jpeg

, 0xffd8, - . !

JPEG file in hex editor

, , , JSON. , , . , . , , , .


MIME . application/json, JSON. , . :

  • ( MIME) (, , , ...), MIME-. (, , , - , FAT32, NTFS, ext4...). , , , ( -, ).

  • . , MIME-?


, ? : .

JSON , . , , . JSON - . , , ( , ) $depth, .

if (json_decode($s_file_path, true, 32)!==null || json_last_error()!==JSON_ERROR_NONE) {
    // Valid JSON
}
0

Source: https://habr.com/ru/post/1665974/


All Articles