4
votes

I have URL (http://forexample.com/index) where I send raw header:

header("HTTP/1.1 401 Some message");

With Guzzle I want to get this raw header message. Unfortunately after request is completed I can't find this message between headers:

$client = new GuzzleHttp\Client();

try {
    $res = $client->post( 'http://forexample.com/index' );
} catch ( GuzzleHttp\Exception\BadResponseException $e ) {
    // On HTTP response other than 200 Guzzle throws an exception
    $res = $e->getResponse();
}

var_dump( $res->getHeaders() );

Let's say if I call this URL with native PHP function get_headers:

var_dump( get_headers( 'http://forexample.com/index' ) );

I get all the headers. So any ideas?

1
Is it not the HTTP status code you're after?N.B.
Nope, I want to get the status message - "Some message".Bounce
Then you are after $res->getReasonPhrase(). However, the reason phrase is absolutely unnecessary if you have the status code. You shouldn't rely on the phrase, only on the status code, but your code is your code and you do what you deem fit. Good luck.N.B.
The getReasonPhrase returns "Unauthorized" message which is actually related to response code. But I need to get "Some message" message :)Bounce
This brings us back to my original comment - you are after the status code, but the issue is that you don't know that yet. Looking at the source of Guzzle Response, it appears one must pass the arbitrary human readable message to it - if nothing is passed via constructor options, then it extracts the message using the status code. I understand that you want the human readable phrase, but it seems that the default class for handling responses won't give the one that remote service returns, but the one that corresponds to the map with status codes.N.B.

1 Answers

2
votes

Guzzle Has predefined status messages for various codes. See here.

So your message will be replaced by that message based on sent code. And default message can be fetched by,

$res->getReasonPhrase();

UPDATE

I know why we are not getting "Some message" with $res->getReasonPhrase(); function. The problem(?) lies here on line number 76.

isset($startLine[2]) ? (int) $startLine[2] : null

In above line, $startLine[2] is the 'Some message' you supplied in header, but due to int casting, results in 0 and due to following piece of code here replaced by default message.

if (!$reason && isset(self::$phrases[$this->statusCode])) {
    $this->reasonPhrase = self::$phrases[$status];
} else {
    $this->reasonPhrase = (string) $reason;
}

I am sure there must be some reason behind int casting but I have created a pull request by replacing int with string just to know if there is any reason behind it. I hope they reject my pull request and tell me why I am wrong and int casting is indeed correct.

UPDATE

Pull request has been accepted and been merged in to master. So in future version this bug would have been fixed.