获取“内容类型"PHP中的请求标头

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

我正在用 PHP 实现一个 REST 服务.该服务应该能够支持多种输入和输出格式(JSON、XML).出于这个原因,我想检查请求标头 Accept" 和 Content-Type" 以了解客户端发送和请求的内容类型.

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 headers "Accept" and "Content-Type" for the type of content sent and requested by the client.

访问 "Accept" 标头就像使用 $_SERVER['HTTP_ACCEPT'] 一样简单.但是访问 "Content-Type" 标头似乎是一项艰巨的任务.我搜索了 PHP 文档和网络,但提供的唯一解决方案是使用 PHP 函数 apache_request_headers() 仅当 PHP 作为 Apache 模块安装时才受支持,这在我的案例.

Accessing the "Accept" header is a simple as using $_SERVER['HTTP_ACCEPT']. But accessing the "Content-Type" header seems to be a difficult task. I searched the PHP documentation and the web, but the only solution offered was the use of the PHP function apache_request_headers() which is only supported when PHP is installed as an Apache module, which is not true in my case.

所以我现在的问题是:如何访问请求的标头Content-Type"?

So my question now: How can I access the header "Content-Type" of a request?

推荐答案

普通 (GET) 请求没有 Content-Type 标头.对于 POST 请求,它将显示为 $_SERVER["CONTENT_TYPE"],其值类似于 multipart/form-data 或 application/x-www-form-urlencoded.

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.

这是 CGI/1.1 规范强制要求的:http://www.ietf.org/rfc/RFC3875.

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

相关文章