如何从 PHP 中的 HTTP Accept 标头中选择内容类型

2022-01-17 00:00:00 http-headers php

我正在尝试构建一个符合标准的网站框架,该框架将 XHTML 1.1 作为 application/xhtml+xml 或 HTML 4.01 作为 text/html 服务,具体取决于浏览器的支持.目前它只是在接受标头中的任何位置查找application/xhtml+xml",如果存在则使用它,但这并不灵活——text/html 可能有更高的分数.此外,当添加其他格式(WAP、SVG、XForms 等)时,它会变得更加复杂.那么,有没有人知道一段经过试验和测试的 PHP 代码,可以从服务器提供的字符串数组中选择客户端最支持的数组,或者根据客户端得分排序的列表?

I'm trying to build a standard compliant website framework which serves XHTML 1.1 as application/xhtml+xml or HTML 4.01 as text/html depending on the browser support. Currently it just looks for "application/xhtml+xml" anywhere in the accept header, and uses that if it exists, but that's not flexible - text/html might have a higher score. Also, it will become more complex when other formats (WAP, SVG, XForms etc.) are added. So, does anyone know of a tried and tested piece of PHP code to select, from a string array given by the server, either the one best supported by the client or an ordered list based on the client score?

推荐答案

您可以利用 apache 的 mod_negotiation 模块.这样您就可以使用该模块提供的所有协商功能,包括您自己的偏好内容类型(例如,我真的想交付应用程序/xhtml+xml,除非客户端非常喜欢别的东西").基本解决方案:

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:

AddHandler type-map .var

创建一个.htaccess文件作为内容

  • 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

    <?php
    echo 'selected type: ', substr($_SERVER['PATH_INFO'], 1);

    作为内容.

  • 请求 http://localhost/whatever/foo.var
  • 为此,您需要启用 mod_negotiation、AddHandler 和 AcceptPathInfo 没有被 $_SERVER['PATH_INFO'] 禁用.
    使用我的 Firefox 发送接受:text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8"并且示例 .var 映射的结果是选定类型: xhtml".
    您可以使用其他调整"来摆脱 PATH_INFO 或请求 foo.var 的需要,但基本概念是:让 mod_negotiation 以脚本可以的方式将请求重定向到您的 php 脚本读取"选定的内容类型.

    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.

    那么,有没有人知道一段经过试验和测试的 PHP 代码可供选择
    So, does anyone know of a tried and tested piece of PHP code to select

    这不是一个纯粹的 php 解决方案,但我想说 mod_negotiation 已经过试验和测试 ;-)

    It's not a pure php solution but I'd say mod_negotiation has been tried and tested ;-)

    相关文章