问题
I'm testing my code, and i have some problem with header. In each api i use
$headers = getallheaders();
to get that, and this works fine when i test with the app or crhome postman extension. When i lauch my test, like this
$client = $this->createClient();
$client->request('GET', '/api/shotcard',
['qrcode'=>'D0m1c173'], [],
['HTTP_API_TOKEN' => 'abc123']
);
$this->assertEquals(200, $client->getResponse()->getStatusCode());
where i try to shot a card with that qrcode with a user with that test token (not the token i'll use in the application), i see a call like this here: https://stackoverflow.com/a/11681422/5475228 . The test fails in this way:
PHP Fatal error: Call to undefined function AppBackendBundle\Controller\getallheaders() in /var/www/pitstop/src/AppBackendBundle/Controller/ApiController.php on line 42
回答1:
From this article:
If you use Nginx, PHP-FPM or any other FastCGI method of running PHP you’ve probably noticed that the function
getallheaders()
does not exist. There are many creative workarounds in the wild, but PHP offers two very nice features to ease your pain.
From user contributed comments at getallheaders()
function on PHP manual by joyview at gmail dot com
if (!function_exists('getallheaders')) {
function getallheaders() {
$headers = [];
foreach ($_SERVER as $name => $value) {
if (substr($name, 0, 5) == 'HTTP_') {
$headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value;
}
}
return $headers;
}
}
回答2:
i resolve in that way(thanks to https://stackoverflow.com/a/11681422/5475228)
private function request_headers($type, Request $request)
{
if(function_exists("getallheaders"))
{
if($header = getallheaders()[$type])
{
return $header;
}
}
return $request->headers->get($type);
}
so the normal request from app get header with getallheaders(), the request from PHPUnit get it from Request object. I don't know why (if someone can explain) but works.
回答3:
A slight variation from @Matteos code which removes Mod-Rewrite and adds in Content-Length and Content-Type which are normally returned by getallheaders()
. Interestingly, the case of the array keys returned by getallheaders()
seems to be all over the place and not consistent whereas obviously this version ensures consistency.
$allHeaders = array();
foreach($_SERVER as $name => $value) {
if($name != 'HTTP_MOD_REWRITE' && (substr($name, 0, 5) == 'HTTP_' || $name == 'CONTENT_LENGTH' || $name == 'CONTENT_TYPE')) {
$name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', str_replace('HTTP_', '', $name)))));
$allHeaders[$name] = $value;
}
}
来源:https://stackoverflow.com/questions/41427359/phpunit-getallheaders-not-work