php set status code

To set the HTTP status code in PHP, you can use the http_response_code function. This function sets the HTTP status code for the current script and also sends a corresponding header to the client.

Here’s an example of how you can use it:

<?php
// Set the status code to 404 (Not Found)
http_response_code(404);

// You can also use one of the predefined constants for common status codes
// For example, to set the status code to 301 (Moved Permanently)
http_response_code(HTTP_MOVED_PERMANENTLY);
?>

Note that you should call this function before you send any output to the client, as the status code must be sent as part of the HTTP headers.

You can also use the header function to set the status code. For example:

<?php
// Set the status code to 404 (Not Found)
header("HTTP/1.0 404 Not Found");

// You can also use one of the predefined constants for common status codes
// For example, to set the status code to 301 (Moved Permanently)
header("HTTP/1.1 301 Moved Permanently");
?>

This method allows you to set the status code and the status message, which can be useful if you need to set a custom status message.

Leave a Comment