bayfrontmedia / php-http-response
Easily send HTTP responses.
Installs: 1 540
Dependents: 4
Suggesters: 0
Security: 0
Stars: 6
Watchers: 2
Forks: 1
Open Issues: 0
Requires
- php: ^8.0
- ext-json: *
README
Easily send HTTP responses.
License
This project is open source and available under the MIT License.
Author
Requirements
- PHP
^8.0
- JSON PHP extension
Installation
composer require bayfrontmedia/php-http-response
Usage
- reset
- setStatusCode
- getStatusCode
- removeHeaders
- setHeaders
- getHeaders
- setBody
- getBody
- send
- sendJson
- redirect
reset
Description:
Resets all headers (including status code) and body.
Parameters:
- None
Returns:
- (self)
Example:
$response->reset();
setStatusCode
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());
}
getStatusCode
Description:
Returns the status code and associated phrase to be sent with response.
Parameters:
- None
Returns:
- (array)
Example:
print_r($response->getStatusCode());
removeHeaders
Description:
Sets header values to be removed with the response.
Parameters:
$headers
(array)
Returns:
- (self)
Example:
$response->removeHeaders([
'X-Powered-By'
]);
setHeaders
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
]);
getHeaders
Description:
Returns array of headers to be sent with the response.
Parameters:
- None
Returns:
- (array)
Example:
print_r($response->getHeaders());
setBody
Description:
Sets body to be sent with the response.
Parameters:
$body
(string)
Returns:
- (self)
Example:
$response->setBody('This is the response body.');
getBody
Description:
Returns body to be sent with the response.
Parameters:
- None
Returns:
- (string)
Example:
echo $response->getBody();
send
Description:
Sends response.
Parameters:
- None
Returns:
- (void)
Example:
$response->send();
sendJson
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'
]);
redirect
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());
}