phphttp-status-codes

PHP http_response_code doesn't seem to work. I *must* be doing something wrong


Building a webhook receiver in PHP 7.4.30.

I can receive absolutely fine. No problems there :-)

However, we need to carry our synchronous validation on the JSON and send back a 400 bad request and a JSON with explanations as to why it failed validation.

So, there are two parts...

1: I'm testing the receving php with simply a header to "reject" any connection and tried many different variations depending on the results of my endless searching:

<?php
http_response_code('400');

die();
?>

Results in a blank screen, not a 400. Changed to 404 to test and it still shows a blank screen.

Referring to PHP: How to send HTTP response code? I tried

<?php
header("HTTP/1.1 400 Bad Request");
die();
?>

...which results in a blank page again.

Also tried

<?php
$sapi_type = php_sapi_name();
if (substr($sapi_type, 0, 3) == 'cgi')
    {header("Status: 404 Not Found");}
else
    {header("HTTP/1.1 404 Not Found");}

die();
?>

which... you guessed it... is just a blank page.

I must be barking completely up the wrong tree, and wondered if you could guide me to how to reject the message via the webhook call? I need to be able to reject it with a response body.

1a. Response with HTTP 403 return code,
response body
{
senderUniqueReference : S-005-03458900823-SUPP-20222313-12345687A
transactionId : T-006-1234567890-SUPP-20220401-1234CC ,
sentTimestamp : 2021-12-25T06:06:12.45",
message , XYZ123 - That's not our equipment
}

Solution

  • You should use the browser's network tool to see what HTTP response code was actually returned by the server for any given request. As M. Eriksson noted in the comments, the graphical display you may or may not get for a specific status code is at the whim of the browser, and has nothing to do with what your PHP code did.

    You can send a response body with any HTTP response code. If you echo something along with those codes, I'd expect the client will see it.

    http_response_code('400');
    echo "Your request was not accepted";
    die();
    

    N.B. if you're testing something which is ultimately supposed to be a webhook response, it's not really intended for sending back to a browser anyway, so you might be better to test with a tool like PostMan or something similar.