Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 $_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?

like image 618
Kumar Kush Avatar asked Dec 09 '11 11:12

Kumar Kush


People also ask

How can I get header content in PHP?

The get_headers() function in PHP is used to fetch all the headers sent by the server in the response of an HTTP request. Parameters: This function accepts three parameters as mentioned above and described below: $url: It is a mandatory parameter of type string. It defines the target URL.

How do I read any request header in PHP?

Receiving the request header, the web server will send an HTTP response header back to the client. Read any request header: It can be achieved by using getallheaders() function. Example 2: It can be achieved by using apache_request_headers() function.

How do I access my uploaded files in PHP?

In PHP, we can access the actual name of the file which we are uploading by keyword $_FILES[“file”][“name”]. The $_FILES is the by default keyword in PHP to access the details of files that we uploaded. The file refers to the name which is defined in the “index. html” form in the input of the file.

What PHP can do with header () command?

The header() function in PHP sends a raw HTTP header to a client or browser. Before HTML, XML, JSON, or other output is given to a browser or client, the server sends raw data as header information with the request (particularly HTTP Request).


2 Answers

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.

like image 107
lorenzo-s Avatar answered Oct 17 '22 03:10

lorenzo-s


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().

like image 24
Kae Verens Avatar answered Oct 17 '22 01:10

Kae Verens