What is the use of the header() function in PHP?

The header() function sends a raw HTTP header to the browser, before the page content. With headers you can give instructions to the browser.

Common uses of header():

  • Redirect the user to another page (Location header).
  • Tell the type of response, like JSON (Content-Type header).
  • Force a file download (Content-Disposition header).
  • Control browser cache (Cache-Control header).
  • Set the HTTP status code, for example 404 or 301.
<?php
header("Content-Type: application/json");

echo json_encode(["status" => "ok"]);
?>

Output:

Tutorials Class - Output Window

{“status”:”ok”}

Note: header() must be called before any output, even a blank space. Otherwise PHP shows the “headers already sent” warning. Full details and more examples are in PHP header() Function.

Learn more about the similar topics:
Tutorials
PHP Forms Handling
PHP Send Mail
PHP header() Function
PHP mail() Function
Exercises & Assignments
Create a PHP Form with 2 fields Name and Hobbies
Interview Questions & Answers
What are the form method Attribute available for submitting?
How can we submit a form without a submit button?
What is the difference between GET and POST method in PHP?
How to redirect a page in PHP?
How to get the browser details of a visitor in PHP?
How to get the previous page (referrer) URL in PHP?
How to get the IP address of a visitor in PHP?