kush.impetus kush.impetus - 8 months ago 24
PHP Question

How to read header of a file uploaded in PHP?

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

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,
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?


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']);

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.