Как выбрать тип контента из HTTP, Принимают заголовок в PHP

Причина указатели, кажется, смущают столько людей, состоит в том, что они главным образом идут с минимальными знаниями в архитектуре ЭВМ. Так как у многих, кажется, нет идеи того, как компьютеры (машина) на самом деле реализованы - работающий в C/C++, кажется посторонним.

развертка А должна попросить, чтобы они реализовали простую основанную на байт-коде виртуальную машину (на любом языке, который они выбрали, Python работает отлично для этого) с системой команд, сфокусированной на операциях указателя (загрузка, хранилище, прямая / косвенная адресация). Тогда попросите, чтобы они записали простые программы для той системы команд.

Что-либо требующее немного больше, чем простое дополнение собирается включить указатели, и они, несомненно, получат его.

18
задан l0b0 26 June 2009 в 14:19
поделиться

3 ответа

You can leverage apache's mod_negotiation module. This way you can use the full range of negotiation capabilities the module offers, including your own preferences for the content type (e,g, "I really want to deliver application/xhtml+xml, unless the client very much prefers something else"). basic solution:

  • create a .htaccess file with
    AddHandler type-map .var
    as contents
  • create a file foo.var with
    URI: foo
    URI: foo.php/html Content-type: text/html; qs=0.7
    URI: foo.php/xhtml Content-type: application/xhtml+xml; qs=0.8
    as contents
  • create a file foo.php with
    as contents.
  • request http://localhost/whatever/foo.var

For this to work you need mod_negotiation enabled, the appropriate AllowOverride privileges for AddHandler and AcceptPathInfo not being disabled for $_SERVER['PATH_INFO'].
With my Firefox sending "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" and the example .var map the result is "selected type: xhtml".
You can use other "tweaks" to get rid of PATH_INFO or the need to request foo.var, but the basic concept is: let mod_negotiation redirect the request to your php script in a way that the script can "read" the selected content-type.

So, does anyone know of a tried and tested piece of PHP code to select
It's not a pure php solution but I'd say mod_negotiation has been tried and tested ;-)
11
ответ дан 30 November 2019 в 06:19
поделиться

Небольшой фрагмент из моей библиотеки:

function getBestSupportedMimeType($mimeTypes = null) {
    // Values will be stored in this array
    $AcceptTypes = Array ();

    // Accept header is case insensitive, and whitespace isn’t important
    $accept = strtolower(str_replace(' ', '', $_SERVER['HTTP_ACCEPT']));
    // divide it into parts in the place of a ","
    $accept = explode(',', $accept);
    foreach ($accept as $a) {
        // the default quality is 1.
        $q = 1;
        // check if there is a different quality
        if (strpos($a, ';q=')) {
            // divide "mime/type;q=X" into two parts: "mime/type" i "X"
            list($a, $q) = explode(';q=', $a);
        }
        // mime-type $a is accepted with the quality $q
        // WARNING: $q == 0 means, that mime-type isn’t supported!
        $AcceptTypes[$a] = $q;
    }
    arsort($AcceptTypes);

    // if no parameter was passed, just return parsed data
    if (!$mimeTypes) return $AcceptTypes;

    $mimeTypes = array_map('strtolower', (array)$mimeTypes);

    // let’s check our supported types:
    foreach ($AcceptTypes as $mime => $q) {
       if ($q && in_array($mime, $mimeTypes)) return $mime;
    }
    // no mime-type found
    return null;
}

пример использования:

$mime = getBestSupportedMimeType(Array ('application/xhtml+xml', 'text/html'));
20
ответ дан 30 November 2019 в 06:19
поделиться

Pear :: HTTP 1.4.1 имеет метод stringgotiateMimeType (массив $ поддерживается, строка $ по умолчанию)

<?php
require 'HTTP.php';

foreach(
  array(
    'text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, */*;q=0.5',
    'text/*;q=0.3, text/html;q=0.8, application/xhtml+xml;q=0.7, */*;q=0.2',
    'text/*;q=0.3, text/html;q=0.7, */*;q=0.8',
    'text/*, application/xhtml+xml',
    'text/html, application/xhtml+xml'
  ) as $testheader) {  
  $_SERVER['HTTP_ACCEPT'] = $testheader;

  $http = new HTTP;
  echo $testheader, ' -> ',
    $http->negotiateMimeType( array('application/xhtml+xml', 'text/html'), 'application/xhtml+xml'),
    "\n";
}

печатает

text/*;q=0.3, text/html;q=0.7, text/html;level=1, text/html;level=2;q=0.4, /;q=0.5 -> application/xhtml+xml
text/*;q=0.3, text/html;q=0.8, application/xhtml+xml;q=0.7, */*;q=0.2 -> text/html
text/*;q=0.3, text/html;q=0.7, */*;q=0.8 -> application/xhtml+xml
text/*, application/xhtml+xml -> application/xhtml+xml
text/html, application/xhtml+xml -> text/html

редактировать: это может быть не так хорошо после все ...
Мой firefox отправляет Accept: text / html, application / xhtml + xml, application / xml; q = 0.9, / ; q = 0.8
text / html и application / xhtml + xml имеют q = 1.0, но PEAR :: HTTP (afaik) не позволяет вам выбрать тот, который вы предпочитаете, он возвращает text / html независимо от того, что вы передаете как $ supported. Этого может хватить, а может и хватить. см. мой другой ответ (ы).
10
ответ дан 30 November 2019 в 06:19
поделиться
Другие вопросы по тегам:

Похожие вопросы: