Exceptions are raised on header retrieval for invalid header lines #146
Description
Per a report I've received recently, calling getHeader()
can result in an exception for malformed header lines, leading to unexpected behavior.
As an example, consider the following:
GET: /some/path
HOST: domain.org
Useragent: h4ckerbot
If a user then attempts to pull the User-Agent header as follows:
$request->getHeader('User-Agent'); // or User_Agent, useragent, etc.
an exception will be thrown, as the header line fails validation (the UserAgent
header class expects a line matching /^user-agent: .*?$/i
).
The expectation is that this would instead return boolean false
(header is not defined and/or malformed), or whatever default value is provided as a second argument to getHeader()
.
In analyzing the interactions between Request::getHeader()
, Headers::has()
/Headers::get()
, and PhpEnviroment\Request::marshalHeaders()
, I think the best approach is to modify Headers::has()
to perform the logic necessary to lazy-load a header if no instance yet exists for it, wrapping that logic in a try/catch block, and returning boolean false
if an exception is caught.
The rationale is because Request::getHeaders()
performs a call to Headers::has()
, and only calls Headers::get()
if the has()
returns true, returning $default
if it does not. Making this change would allow Request::getHeader()
to return $default
in such cases, which is what users expect.