You just need to understand what headers are and what HTTP response is. All PHP does is the creation of this response. And headers always come first. All the HTTP response content is written sequentially, top down, without a possibility to get back; however, you can, say, modify header information with
header_remove.
So, imagine what happens if you echo some data. It means that it's too late to write any header, this step is already passed. Some headers are written implicitly; when you echo some data, and no headers are written, required headers are output first, and then goes the data you echo. Most likely, you created some output before trying to add/modify headers.
If you need to write your custom headers, it should be done in the very beginning of your PHP execution flow (that is not necessarily in first lines of PHP code, where you can have some declarations); it's important that you don't echo anything before you write headers. As soon as you created some output in the body of HTTP response, it's too late to add or modify headers.
See also:
PHP: header — Manual[
^],
How to fix "Headers already sent" error in PHP — Stack Overflow[
^].
—SA