How to select content type from HTTP Accept header in PHP

后端 未结 7 1028
[愿得一人]
[愿得一人] 2020-12-16 13:10

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. Curre

相关标签:
7条回答
  • 2020-12-16 13:35

    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
      <?php
      echo 'selected type: ', substr($_SERVER['PATH_INFO'], 1);
      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 ;-)

    0 讨论(0)
提交回复
热议问题