Easily send HTTP responses.
This project is open source and available under the MIT License.
- PHP
^8.0
- JSON PHP extension
composer require bayfrontmedia/php-http-response
- reset
- setStatusCode
- getStatusCode
- removeHeaders
- setHeaders
- getHeaders
- setBody
- getBody
- send
- sendJson
- redirect
Description:
Resets all headers (including status code) and body.
Parameters:
- None
Returns:
- (self)
Example:
$response->reset();
Description:
Sets status code to be sent with response.
Parameters:
$status
(int)
Returns:
- (self)
Throws:
Bayfront\HttpResponse\InvalidStatusCodeException
Example:
use Bayfront\HttpResponse\InvalidStatusCodeException;
use Bayfront\HttpResponse\Response;
$response = new Response();
try {
$response->setStatusCode(429);
} catch (InvalidStatusCodeException $e) {
die($e->getMessage());
}
Description:
Returns the status code and associated phrase to be sent with response.
Parameters:
- None
Returns:
- (array)
Example:
print_r($response->getStatusCode());
Description:
Sets header values to be removed with the response.
Parameters:
$headers
(array)
Returns:
- (self)
Example:
$response->removeHeaders([
'X-Powered-By'
]);
Description:
Sets header values to be sent with the response.
Parameters:
$headers
(array)
Returns:
- (self)
Example:
$response->setHeaders([
'X-Rate-Limit-Limit' => 100,
'X-Rate-Limit-Remaining' => 99
]);
Description:
Returns array of headers to be sent with the response.
Parameters:
- None
Returns:
- (array)
Example:
print_r($response->getHeaders());
Description:
Sets body to be sent with the response.
Parameters:
$body
(string)
Returns:
- (self)
Example:
$response->setBody('This is the response body.');
Description:
Returns body to be sent with the response.
Parameters:
- None
Returns:
- (string)
Example:
echo $response->getBody();
Description:
Sends response.
Parameters:
- None
Returns:
- (void)
Example:
$response->send();
Description:
Sets Content-Type as application/json
, and converts the given array to the JSON encoded body.
Parameters:
$array
(array)
Returns:
- (void)
Example:
$response->sendJson([
'results' => [
'user_id' => 5,
'username' => 'some_username'
],
'status' => 'OK'
]);
Description:
Redirects to a given URL using a given status code.
Parameters:
$url
(string)$status = 302
(int): HTTP status code to return
Returns:
- (void)
Throws:
Bayfront\HttpResponse\InvalidStatusCodeException
Example:
use Bayfront\HttpResponse\InvalidStatusCodeException;
use Bayfront\HttpResponse\Response;
$response = new Response();
try {
$response->redirect('https://www.google.com', 301);
} catch (InvalidStatusCodeException $e) {
die($e->getMessage());
}