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?
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.
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.
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.
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).
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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With