Php response mime type

Like my Create a Basic Web Service Using PHP, MySQL, XML, and JSON illustrates, even though a file’s extension ends in PHP, you can still tell the browser that you’re outputting a different content type. Here are a few of the more popular content types used on the internet.

Atom

header('Content-Type: application/atom+xml');

CSS

header('Content-Type: text/css');

Javascript

header('Content-Type: text/javascript');

JPEG Image

header('Content-Type: image/jpeg');

JSON

header('Content-Type: application/json');

PDF

header('Content-Type: application/pdf');

RSS

header('Content-Type: application/rss+xml; charset=ISO-8859-1');

Text (Plain)

header('Content-Type: text/plain');

XML

header('Content-Type: text/xml');

Just because a file ends in .PHP doesn’t mean it responds with XHTML — respond however you’d like!

Recent Features

Detect DOM Node Insertions with JavaScript and CSS Animations

Detect DOM Node Insertions with JavaScript and CSS Animations

Serving Fonts from CDN

Serving Fonts from CDN

Incredible Demos

9 More Mind-Blowing WebGL Demos

9 More Mind-Blowing WebGL Demos

FileReader API

FileReader API

Discussion

Great list of mime types.
Perhaps I’d just be careful about the charset at the RSS example. People could add it blindly and suddenly accented characters would stop working if the rest of the site is using other encodings, like utf-8.

Interesting list. Nothing new, but still nice. BTW Javascript and XML should be application, text is obsolete.

Источник

Using MIME Type Header [PHP Code]

MIME (Multipurpose Internet Mail Extensions) type is a standard way of describing a data type in the body of an HTTP message or email. The MIME type is passed in the Content-Type header. For example, the Content-Type: text/html header tells the browser that it received an HTML page. Based on this MIME-type header, the browser can parse and display the received HTML page correctly. In this PHP MIME Type Header example, we are sending a request to ReqBin echo URL with Content-Type HTTP header. Click Click Send to run PHP MIME Type Header example online and see results. The PHP code was automatically generated for the Mime Type example.

POST /echo/post/json HTTP/1.1 Host: reqbin.com Accept: application/json Content-Type: application/json Content-Length: 79

PHP code for Mime Type example

PHP code for Mime Type Example

This PHP code snippet was generated automatically for the Mime Type example.

Читайте также:  Random sample python это

What is MIME Type?

MIME stands for Multipurpose Internet Mail Extensions.It is a fundamental part of communication protocols such as HTTP. The MIME type is required when you need to transfer non-text data. MIME was originally designed to extend the capabilities of email to support more data types such as non-ASCII text files and binary files such as images, PDFs, and executables. The use of MIME is not limited to email. It is now actively used in all communications over the Internet to describe the type of data sent to or from a server. It is often referred to as a media type or MIME content type. In HTTP, the MIME-type is part of the Content-Type header of an HTTP message and defines the data type in the body of an HTTP request or response. Setting the correct MIME data type in the body of the message is critical for both HTTP requests and responses and allows you to control how the request is interpreted by the client and server. Web servers and browsers have a list of well-known file extensions and MIME types. This helps them identify and interpret all known file types, regardless of the operating system and hardware used by the user.

What is the MIME structure?

MIME types usually consist of three parts: type, subtype, and optional parameters, separated by a forward slash «/» without spaces. The MIME type is not case-sensitive but is usually written in lowercase letters. A MIME type must have a type as well as a subtype. Each type has its own set of possible subtypes. For example, text/plain; charset=UTF-8 describes data in plain text format with UTF-8 encoding. The following is an example of the MIME type of an HTTP request:

POST /echo/post/json HTTP/1.1 Host: reqbin.com Content-Type: application/json Content-Length: 81
HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 . 

How to pass multiple objects in a single MIME message?

The MIME format supports the transmission of multiple objects in one message. Entities can be transferred not only in the form of a single-level sequence but also in the form of a hierarchy with the nesting of elements into each other. The multipart/* media type is used to indicate multiple contents. To transmit a multipart message, a boundary parameter is added to the Content-Type header, which denotes the sequence of characters that separate the parts of the message. The border can consist of numbers, letters, and symbols () + _, -. /: = ?.

Читайте также:  Интерфейс comparable java примеры

The beginning of each part of the message is indicated by the string —boundary. The end of the last message is indicated by the string —boundary—. At the very beginning of the included part, there are headers that describe its content (Content-Type, Content-Length, etc.). If Content-Type is not specified, then text/plain is used by default.

POST echo/post/form HTTP/1.1 Host: reqbin.com Content-Type: multipart/form-data; boundary=-------10591404156 Content-Length: 554 ---------10591404156 Content-Disposition: form-data; name="text" some text ---------10591404156 Content-Disposition: form-data; name="file1"; filename="readme.txt" Content-Type: text/plain [readme.txt file contents] ---------10591404156 Content-Disposition: form-data; name="file2"; filename="image.png" Content-Type: image/png [image.png file contents] ---------10591404156--

Common MIME Types

  • Images: image/jpeg, image/png, image/gif, image/svg+xml
  • Files: text/plain, application/pdf, application/zip
  • Applications: application/octet-stream, application/pkcs8
  • Media: audio/mpeg, video/mp4, video/mpeg
  • Data: application/json, application/xml

See also

Generate code snippets for PHP and other programming languages

Convert your Mime Type request to the PHP, JavaScript/AJAX, Node.js, Curl/Bash, Python, Java, C#/.NET code snippets using the PHP code generator.

Источник

Работа с MIME-типами в PHP

«Internet Media Types» или «Медиа типы» — является стандартом RFC 6838, который описывает формат файла. Причем браузеры используют MIME-типы в качестве основного критерия, не воспринимая расширения файлов.

MIME-тип состоит из типа и подтипа — двух значений разделённых « / », без использования пробелов и в нижнем регистре, например HTML страница:

Полный список MIME типов можно посмотреть тут.

К медиа типу может быть добавлен параметр для указания дополнительных деталей (например кодировка):

Как узнать MIME-тип загруженного файла

При загрузке файла через форму, MIME-тип файла доступен в массиве $_FILES , например:

Для определения MIME уже загруженного файла существует PHP-функция mime_content_type().

echo mime_content_type(__DIR__ . '/image.png'); // image/png echo mime_content_type(__DIR__ . '/text.txt'); // text/plain

При работе с изображениями, MIME-тип можно получить с помощью функции getimagesize():

$filename = __DIR__ . '/image.png'; $info = getimagesize($filename); print_r($info);

Результат:

Array ( [0] => 221 [1] => 96 [2] => 3 [3] => width="221" height="96" [bits] => 8 [mime] => image/png )

Важно помнить что при проверке файлов нельзя полагаться только на проверку MIME, т.к. его значение может быть скомпрометировано. Поэтому нужно проводить более детальную проверку (например по размеру изображения или его пересохранить в предполагаемом формате).

Читайте также:  Java вызов метода наследника

Отправка файлов из PHP

В PHP-скриптах, перед отправкой файлов клиенту, необходимо отправлять заголовок Content-Type , например файл XML:

$content = '. '; header("Content-Type: text/xml; charset=utf-8"); echo $content; exit();
$file = ROOT_DIR . '/market.zip'; header('Content-type: application/zip'); header('Content-Transfer-Encoding: Binary'); header('Content-length: ' . filesize($file)); header('Content-disposition: attachment; filename="' . basename($file) . '"'); readfile($file); exit();

Вывод изображения в зависимости от расширения файла:

$filename = __DIR__ . '/image.png'; $ext = mb_strtolower(mb_substr(mb_strrchr($filename, '.'), 1)); switch ($ext) < case 'png': header('Content-type: image/png'); break; case 'jpg': case 'jpeg': header('Content-type: image/jpeg'); break; case 'gif': header('Content-type: image/gif'); break; case 'wepb': header('Content-type: image/webp'); break; >readfile($filename); exit();

Источник

Оцените статью