How to get headers in PHP?

by darrion.kuhn , in category: PHP General , 9 months ago

How to get headers in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lottie , 3 months ago

@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');
}