my question is: Is there some relation between a file extension and it's mime type? I mean, if i get a file, for instance, .php and change it's extension to .png will also change it's mime type?
3 Answers
File extensions are hints as to the kind of data the file contains. MIME types are labels for the kind of data in a file. One file extension maps to at most one MIME type. One MIME type maps to zero or more file extensions. A good example is image/jpeg, which maps to both .jpg and .jpeg.
Theory aside, the MIME type a browser gives you is usually reliable, but if you require certainty you must then assume the browser has been compromised.
In such case, on the server using PHP, you can check that a given file matches a given MIME type with the FInfo extension:
$path = '/path/to/your/file.pdf';
$info = finfo_open(FILEINFO_MIME_TYPE);
switch (finfo_file($info, $fpath)) {
case 'application/pdf':
// hooray, this is what you want
// do whatever
break;
default:
throw new RuntimeException('I said give me a PDF!');
}
Or if you want a simple function:
function is_mime_type($path, $mime) {
return (finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path) === $mime);
}
if (is_mime_type('/path/to/file.pdf', 'application/pdf')) {
// hooray
}
Here is a similar answer that documents other approaches to accomplish this goal.
And here's an answer asking about the mapping between file extensions and MIME types.
2 Comments
Short answer: Yes.
Slightly longer answer: Mime types and file extensions provide hints to how to deal with a file. Whereas file extensions are commonly used for your OS to decide what program to open a file with, Mime types are used by your browser to decide how to present some data (or the server on how to interpret received data). Both are optional but it's a good practice to have an agreement. Changing the mime type a file is served as depends on your webserver. I believe Apache has settings somewhere to map from extensions to mime types. If you have your own back end serving content you can potentially serve content with any arbitrary mime type, for example, in PHP:
<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');
...
or
<?php
header('Content-Type: application/javascript');
echo "//script code here"
fileorfinfo_file) to identify the actual content.