PHP Content-Type Header
In PHP, the Content-Type
header is used to specify the type of data that is being sent in the HTTP response. This header informs the browser or client about the type of content it should expect from the server. Here are some common content types and how to set the Content-Type
header in PHP:
HTML:
header("Content-Type: text/html");
This is used for HTML documents.
Plain Text:
header("Content-Type: text/plain");
This is used for plain text content.
JSON:
header("Content-Type: application/json");
This is used when the response contains JSON data.
XML:
header("Content-Type: application/xml");
This is used for XML documents.
Images:
header("Content-Type: image/jpeg"); // for JPEG images
header("Content-Type: image/png"); // for PNG images
This is used for serving image files.
PDF:
header("Content-Type: application/pdf");
This is used for serving PDF documents.
When setting the Content-Type
header in PHP, it's important to do so before any actual output (e.g., echo
or HTML content). The header()
function is used to send a raw HTTP header to the client. Here's an example:
<?php
header("Content-Type: application/json");
// Your JSON data here
echo json_encode(array("name" => "John", "age" => 30));
?>
In this example, the Content-Type
is set to application/json
before outputting JSON data. This informs the client that the response contains JSON content, allowing it to handle the data appropriately.
Remember to be cautious when manually setting headers, as they must be sent before any actual content. Failure to do so may result in an error. Additionally, PHP provides functions like header()
to set other HTTP headers for controlling caching, redirects, and more.
Thank you.