I’m wondering about what PHP headers are. I use PHP strictly for HTML completion and I thought I had to send text/html header when the output was text and then image/jpeg header from a separate script which was used as source in an image tag but then someone suggested me to take away the headers because they made nothing.
I did and everything was the same as before. This made me wonder: What are headers? When are they used? (both from an HTML perspective but also from some (?) other perspective) And why could I remove mine?
There are lots of different HTTP headers that mean different things. PHP will give you defaults for the important ones if you don’t set them yourself.
I think the header you’re specifically talking about is
Content-Type. This tells the browser what kind of file you’re sending it. If you saytext/html, it will try to display what you give it as a web page. If you sayapplication/pdf, it’ll try to display or download it as a PDF file.PHP defaults to sending
Content-Type: text/html. If that’s all you want, you don’t have to callheader('Content-Type: ...');at all. However, if you are using any non-ASCII Unicode characters, you may wish to setContent-Typetotext/html;charset=something, wheresomethingis the encoding you’re using for them (often,utf-8). Otherwise the browser will have to guess and might get it wrong. The commonly-seen<meta http-equiv="Content-Type" content="text/html;charset=something"/>tag is an alternative way of doing the same thing; if you want to be really safe about it, you can use both.If you serve a JPEG image as
text/html, which is what will be happening if you follow “someone”’s questionable advice by removing theheader()call, then going to the URL of the image in the browser will try to display the binary image as HTML, which will give you a big old load of garbage on the screen. That’s not very good, really.However in many browsers, such a broken JPEG will still usually work when you point an
<img src>tag at it. This is because when you use an<img>, the browser knows it’s going to be fetching an image, and ignores you when you say it’s actually HTML. It then has to to ‘sniff’ the contents of the file to see whether it looks like a JPEG, a GIF, a PNG, or some other kind of image it knows about, so it knows how to display it. Browsers have done this because there are so many poorly-written sites out there that forget to send the header. Boo!So definitely send
header('Content-Type: image/jpeg')when you’re writing a JPEG, or any other non-HTML type. For HTML pages, you can often get away without it.