The Correct Mime Type For Plain Text
There has been some confusion about which mime type is correct for plain text on the web, and while both might work, only one is correct.
By. Jacob
Edited: 2019-12-02 20:56
When you are working with Content-Type's and plain text, you will probably have noticed people write the mime type in two different ways, text/txt and text/plain, but only one is actually correct.
Both seem to work, possibly because browsers default to showing content in plain text when they do not understand the mime type? Anyway, this might be why people do not notice the mistake.
The correct mime type to use for plain text is text/plain.
For the Content-Type header, the correct HTTP response would look like this:
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
In PHP, you would use the header() function to change the content type:
header("Content-Type: text/plain; charset=utf-8");
// body output is sent after sending response headers
Content-type for plain text
Considering that both text/plain and text/txt is working, why not just use the txt one? Well, clients might not understand it for one.
There are cases where actual mistakes got worked into the HTTP protocol, such as the missspelled Referer header (an r is missing), this is not the case with text/txt. The reason it is still working, is that browsers support it.
The error might possible be due to the fact that plain text files in Windows are using the .txt file extension.
It is not enough to simply use the right mime type, you should also set the character set. A common character set is utf-8, which we can also set via the Content-Type header.
It is important to note that the Content-Type header will override meta declarations in HTML documents.
Delivering static files with PHP
It is generally not recommended to use PHP's bare File functions, such as file_get_contents to read static files.
See also: Avoid File_get_contents and File_put_contents
How to send static files to the browser is covered in this article:
Tell us what you think: