How to read header of a file uploaded in PHP?

2020-06-19 23:24发布

问题:

Can we read the header information of a file in PHP to determine the type of file uploaded?.

I don't want to rely on $_FILES['control_name_from_client']['type']. As we know that this property determines the file type by reading the extension of the file uploaded.

What if the user renames, say test.jpg -> test.xls. In that case, $_FILES['control_name_from_client']['type'] will show the type as application/vnd.ms-excel instead of image/jpeg. It is but natural this can create problems if a code has to be executed which reads the XLS file to fetch data for some processing.

Any suggestions please?

回答1:

Try finfo_file(). You have to call it passing the filepath. Example:

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES['control_name_from_client']['tmp_name']);
finfo_close($finfo);

You need the Fileinfo extension. As PHP manual says:

The functions in this module try to guess the content type and encoding of a file by looking for certain magic byte sequences at specific positions within the file. While this is not a bullet proof approach the heuristics used do a very good job.



回答2:

as far as I'm aware, there is no such function in PHP, but if you have access to the CLI (and are running Linux), you could use the "file" command through system().



回答3:

There used to be the mime_magic extension in older versions of PHP, but that's deprecated now in favour of finfo_file, which does use file signatures to test the filetype, not purely the extension.



回答4:

Dunno what "header" you are talking about, but from the security point of view the only thing you really have to pay attention to is a filename extension.
Just because your web-server would judge your file by it.

To test if uploaded file being valid data for some particular application, you have to use this application-specific routine, there are no universal tool in PHP. you can use imagemagick for images, getid3 for the mp3 files, fffmpeg for the movies and so on.

But of course whole file have to be employed, checking just "header" doesn't guarantee that entire file is valid.