Get “Content-Type” header of request in PHP

前端 未结 3 611
天命终不由人
天命终不由人 2020-12-01 13:29

I\'m implementing a REST service in PHP. This service should be able to support multiple input and output formats (JSON, XML). For that reason I want to check the request he

相关标签:
3条回答
  • 2020-12-01 14:17

    Normal (GET) requests do not have a Content-Type header. For POST requests it would appear as $_SERVER["CONTENT_TYPE"], with a value like multipart/form-data or application/x-www-form-urlencoded.

    This is mandated by the CGI/1.1 specification: http://www.ietf.org/rfc/rfc3875.

    0 讨论(0)
  • 2020-12-01 14:22

    You'll need to manually instruct Apache to supply the Content-Type header (plus any other headers you want).

    Pop something like this in your .htaccess file or virtual host:

    RewriteEngine on
    RewriteRule .* - [E=HTTP_CONTENT_TYPE:%{HTTP:Content-Type},L]
    

    And voila, you just synthesised your very own $_SERVER['HTTP_CONTENT_TYPE']!

    Edit:

    I assume you're running PHP as CGI with Apache so you can use verbs other than GET and POST, as most rest services do. If you're using another web server or largely unheard-of PHP SAPI, you'll need to use a similar trick; PHP as CGI simply doesn't have access to request headers outside the contents of $_SERVER, no matter what other mechanisms you use - $_ENV, apache_request_headers(), even the classes in the php_http extension will all be empty.

    0 讨论(0)
  • 2020-12-01 14:22

    You can also get the content type (like "text/html") with this :

    echo split(',', getallheaders()['Accept'])[0];
    

    or

    echo get_headers('http://127.0.0.1', 1)["Content-Type"]
    

    Update

    Like Benjamin said, apache_request_headers is available with FastCGI from 5.4.0 and from internal PHP server since 5.5.7.

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