How to send HTTP response code in PHP?

HTTP Response code: There are three approaches to accomplish the above requirement, depending on the version.

For PHP versions 4.0: In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one.

header("HTTP/1.1 200 OK");

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

$sapitype = php_sapi_name();
if (substr($sapitype, 0, 3) == 'cgi')
    header("Status: 404 Not Found");
else
    header("HTTP/1.1 404 Not Found");

chevron_right


For PHP versions 4.3: There are obviously a few problems when using first method. The biggest one is that it is partly parsed by PHP and is poorly documented. Since the version 4.3, the header() function has an additional 3rd argument through which we can set the response code. but to use the first argument should be a non-empty string.

header(':', true, 400);
header(‘X_PHP_Response_Code: 400', true, 400);

The second one is recommended. The header field name in this variant is not standardized and can be modified.



For PHP versions 5.4: This versions uses http_response_code() function to makes things easier.

http_response_code(400);

Example: This example uses http_response_code() function to send HTTP response code.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
error_reporting(E_ERROR | E_PARSE);
  
// Initialize a variable into domain name
  
// Function to get HTTP response code 
function get_http_response_code($domain1) {
    $headers = get_headers($domain1);
    return substr($headers[0], 9, 3);
}
  
// Function call 
$get_http_response_code = get_http_response_code($domain1);
  
// Display the HTTP response code
echo $get_http_response_code;
  
// Check HTTP response code is 200 or not
if ( $get_http_response_code == 200 )
    echo "<br>HTTP request successfully";
else
    echo "<br>HTTP request not successfully!";
      
?>

chevron_right


Output:

200
HTTP request successfully


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.