@darrion.kuhn
You can use the header
function in PHP to set a custom HTTP header for a response. This function must be called before any actual output is sent to the browser, so you should place it at the top of your script.
Here's an example of how you can use the header
function to set a custom Content-Type
header:
1 2 3 4 5 |
<?php header('Content-Type: application/json'); // Output your JSON data here echo '{"key": "value"}'; |
You can also use the header
function to set multiple headers at once by separating them with a new line. For example:
1 2 3 4 5 6 |
<?php header('Content-Type: application/json'); header('X-Custom-Header: value'); // Output your JSON data here echo '{"key": "value"}'; |
Note that you should use the header
function only after you have checked whether the headers have already been sent. You can use the headers_sent
function to check if the headers have already been sent, like this:
1 2 3 4 5 6 7 |
<?php if (headers_sent()) { // headers already sent, do something here } else { // headers not yet sent, you can safely set them header('Content-Type: application/json'); } |
@darrion.kuhn
You can get headers in PHP using the getallheaders()
function or by accessing the $_SERVER
superglobal array.
1
|
$headers = getallheaders(); |
This function returns an associative array containing all the HTTP headers.
1
|
$headers = $_SERVER;
|
The $_SERVER
superglobal array contains all the server variables, including the HTTP headers.
You can then access individual headers by their keys in the headers array. For example, to get the value of the "User-Agent" header:
1
|
$userAgent = $headers['User-Agent']; |