framework: HTTP headers not working for unit tests

If you try to get a HTTP header via Request::header('HTTP_USER_AGENT') when the request was made through a test case, it always returns “NULL”. If the request was made through the browser everything works fine.

I checked in the symfony source code wether the headers were set (when running the test).

var_dump($server):

array(4) {
  'HTTP_HOST' =>
  string(9) "localhost"
  'HTTP_USER_AGENT' =>
  string(19) "Symfony2 BrowserKit"
  'HTTPS' =>
  bool(false)
}

About this issue

  • Original URL
  • State: closed
  • Created 11 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

@schickling, I was actually running into the same issue when I tried to set/retrieve an Authorization header in my tests.

After reading through the source of Symfony’s Request class I found an overrideGlobals() method which apparently expects all headers to be prefixed with HTTP_. While I’m still unsure of how Symfony calls this method internally, prefixing your headers in that way seems to do the trick.

So, in your tests you’d make the following call:

$this->call('GET', '/api', array(), array(), array("HTTP_CUSTOM"=>"custom header"));

…and you’d retrieve that custom header in your Laravel app with:

Request::header('Custom');

@schickling, this is clearly a Symfony issue/feature. If you look at their tests, you’ll see that this is exactly how they expect to pass and retrieve custom HTTP headers: Symfony/Component/HttpFoundation/Tests/RequestTest.php#L44-L45

Hi! I use AngularJS with Laravel, and have had problems to get the token with $token = Request::header(‘_token’); // Not working

But I found out that you can’t use underscore ‘_’. So: $token = Request::header(‘mytoken’); // Working 😃

Info: make a script in index.blade.php to make a constant with the csrf token:

angular.module("myApp").constant("CSRF_TOKEN", '<?php echo csrf_token(); ?>');

in app.js:

angular.module(‘myApp’, []…).run(function($http,CSRF_TOKEN) {

        console.log('CSRF_TOKEN: ' + CSRF_TOKEN);
    $http.defaults.headers.common['mytoken'] = CSRF_TOKEN;
})

@schickling HTTP_USER_AGENT is not an actual header, it is just a convenience variable that you can access through the $_SERVER array and that is extracted from value of the User-Agent header.

Have you tried using Request::header('User-Agent') instead? This is returning a value both in a browser as well as in a test suite.