无法使用PHP slim框架检索所有请求标头

时间:2016-03-30 18:07:51

标签: php rest http slim slim-3

我正在使用PHP slim框架进行个人项目。出于某种原因,Request in Slim的PSR实现显然是过滤一些标题。我正在尝试设置自定义CSRF令牌,但无法通过$ request-> getHeaders()获取。以下是显示问题的一个示例:

$app->get('/bar', function ($request, $response, $args) {
    echo "PHP's getallheaders() <br>";
    foreach (getallheaders() as $name => $value) {
        echo "$name: $value <br>";
    }
    echo "Slim's GetHeaders() <br>";
    foreach ($request->getHeaders() as $name => $values) {
        foreach ($values as $value) {
            echo "$name: $value <br>";
        }
    }
});

我得到了这个输出:

PHP's getallheaders()
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: null
Accept-Encoding: gzip, deflate
csrf_name: csrf56fc038c2f6eb
csrf_value: 4e077c04dadf22377da2aebc1a8caa78
Cookie: PHPSESSID=41016nbag70gi6shq4u2tg0aq1
Connection: keep-alive

Slim's GetHeaders()
Host: localhost
HTTP_USER_AGENT: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_LANGUAGE: null
HTTP_ACCEPT_ENCODING: gzip, deflate
HTTP_COOKIE: PHPSESSID=41016nbag70gi6shq4u2tg0aq1
HTTP_CONNECTION: keep-alive 

我想了解自定义标题的原因:

csrf_name: csrf56fc038c2f6eb
csrf_value: 4e077c04dadf22377da2aebc1a8caa78 

正被Slim删除。

2 个答案:

答案 0 :(得分:2)

它不是Slim,它是网络服务器。

即使标题名称包含下划线的标头因HTTP规范而有效,但出于安全原因,NginxApache都会默默删除这些标头。通常,您应该只使用包含a..zA..Z-字符的标头。

使用Apache,您仍然可以使用getallheaders()作为apache_request_headers()的别名,在其名称中使用下划线访问标题。

使用Nginx,您可以使用underscores_in_headers on设置在名称中启用带下划线的标头。

答案 1 :(得分:0)

信不信由你,问题是Slim不喜欢用户定义标题中的下划线。一旦我将csrf_name更改为csrfname就可以了:

PHP's getallheaders()
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: null
Accept-Encoding: gzip, deflate
csrfvalue: 4e077c04dadf22377da2aebc1a8caa78
csrfname: csrf56fc038c2f6eb
Cookie: PHPSESSID=5aom8b5q7ottorc9279q9sh4g1
Connection: keep-alive

Slim's GetHeaders()
Host: localhost
HTTP_USER_AGENT: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0
HTTP_ACCEPT: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
HTTP_ACCEPT_LANGUAGE: null
HTTP_ACCEPT_ENCODING: gzip, deflate
HTTP_CSRFVALUE: 4e077c04dadf22377da2aebc1a8caa78
HTTP_CSRFNAME: csrf56fc038c2f6eb
HTTP_COOKIE: PHPSESSID=5aom8b5q7ottorc9279q9sh4g1
HTTP_CONNECTION: keep-alive

所以,不要忘记,删除下划线!!

编辑正如Mika Tuupola所解释的,根本原因是HTTP服务器而不是苗条。