hollodotme / fast-cgi-client

A PHP fast CGI client for sending requests (a)synchronously to PHP-FPM
Other
551 stars 34 forks source link

Retrieve response code #47

Closed proArtex closed 5 years ago

proArtex commented 5 years ago

Is there any way to get response status code?

hollodotme commented 5 years ago

Hi @proArtex! The answer is no and yes. :)

NO

In general the client uses the FastCGI protocol to communicate with the FastCGI server, such as php-fpm. This protocol is not HTTP and does not know about response status codes by itself.

YES

I assume that you're using php-fpm as FastCGI server.

As described in this comment of #27, there are four cases when php-fpm produces an HTTP status header with code 404 or 403. In any other case php-fpm does not produce a HTTP status header.

As soon as your request hits a valid endpoint the server always answers with a plain text response that can include HTTP headers, if your endpoint set those headers. An example for a simple endpoint:

/endpoint.php

<?php

if ( isset( $_REQUEST['hello'] ) )
{
    # Send header with HTTP status code 200 OK
    header( 'Status: 200 OK');
    echo "Hello {$_REQUEST['hello']}";

    return;
}

# Send header with HTTP status code 400 Bad Request
header( 'Status: 400 Bad Request' );
echo "Bad Request, parameter 'hello' is missing.";

That means you are responsible to send the right HTTP status codes if you want to use them in your application.

The plain responses for this endpoint could look like this:

/endpoint.php with QUERY_STRING: hello=proArtex

X-Powered-By: PHP/7.3.5
Status: 200 OK
Content-type: text/html; charset=UTF-8

Hello proArtex

/endpoint.php with empty QUERY_STRING

X-Powered-By: PHP/7.3.5
Status: 400 Bad Request
Content-type: text/html; charset=UTF-8

Bad Request, parameter 'hello' is missing.

Now that you have the status header sent, you can read it using the response object of the lib.

$response->getHeader('Status');

I hope this answers your question.

proArtex commented 5 years ago

@hollodotme thanks for the answer! Now I see that missing of 'Status' header actually means the same as 'Status: 200 OK'.

I actually want to add HEALTHCHECK to php-fpm docker container itself without web server (since it is in separate container). So I'm going to make a little cli wrapper and pack with phar so that I could use it like that:

...
COPY --from=fcgi-healthz:latest /usr/bin/fcgi-healthz /usr/bin/fcgi-healthz
...
HEALTHCHECK CMD fcgi-healthz public/index.php /helathz [--some-option ...] || exit 1

What do you think, useful?

hollodotme commented 5 years ago

Sounds nice @proArtex! Have a look at #45 where we discussed something similar, but for multiple servers/containers.