问题
I am using ZF2 and for some reason, I can get all the headers I send EXCEPT the Authorization header - it's like its filtered out.
I am trying to get all the headers in the controller like this:
public function createAction($data)
{
$request = $this->request;
print_r ($request->getHeaders());
exit();
}
I send the request through cURL like this:
curl -i -H "Accept: test" -H "Authorization: 123456" -H "Content-Type: qwerty" -X POST http://localhost/test
All headers prints out EXCEPT authorization header. I can add any arbitrary header and it prints it out - just no the 'Authorization' header...
I've also tried to get()/has() for the authorization header, yet it does not exist.
回答1:
Works fine for me (ZF2 Version 2.1.4):
curl -i -H "Accept: test" -H "Authorization: 123456" -X POST http://zf2.localhost
Results in:
HTTP/1.1 200 OK
Date: Thu, 11 Apr 2013 09:44:45 GMT
Server: Apache/2.4.3 (Win32) OpenSSL/1.0.1c PHP/5.4.7
X-Powered-By: PHP/5.4.7
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-ch
Pragma: no-cache
Content-Length: 843
Content-Type: text/html
object(Zend\Http\Headers)#168 (3) {
["pluginClassLoader":protected]=>
NULL
["headersKeys":protected]=>
array(4) {
[0]=>
string(9) "useragent"
[1]=>
string(4) "host"
[2]=>
string(6) "accept"
[3]=>
string(13) "authorization"
}
["headers":protected]=>
array(4) {
[0]=>
array(2) {
["name"]=>
string(10) "User-Agent"
["line"]=>
string(23) "User-Agent: curl/7.26.0"
}
[1]=>
array(2) {
["name"]=>
string(4) "Host"
["line"]=>
string(24) "Host: zf2.localhost"
}
[2]=>
array(2) {
["name"]=>
string(6) "Accept"
["line"]=>
string(12) "Accept: test"
}
[3]=>
array(2) {
["name"]=>
string(13) "Authorization"
["line"]=>
string(21) "Authorization: 123456"
}
}
}
With the following code:
$request = $this->getRequest();
var_dump($request->getHeaders());
Use the following to get the value:
$authVal = $request->getHeaders('authorization')->getFieldValue();
Hope this helps :)
回答2:
I finally found the answer here:
http://zend-framework-community.634137.n4.nabble.com/HTTP-Digest-authentication-does-not-work-with-PHP-as-CGi-td4658790.html
Had to add the following to the projects .htaccess:
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
回答3:
hope this will help you in zf2
$headers = $request->getHeaders();
$authorization = $headers->get('Authorization')->getFieldValue();
$request is object of Zend\Http\Request;
来源:https://stackoverflow.com/questions/15945231/getting-request-authorization-header-in-zf2-controller