0
0
PhpHow-ToBeginner · 3 min read

How to Use Header Function in PHP: Syntax and Examples

Use the header() function in PHP to send raw HTTP headers to the browser before any output. It is commonly used for redirects or setting content types by passing a string like header('Location: url') or header('Content-Type: text/html').
📐

Syntax

The header() function sends a raw HTTP header to the client. It must be called before any output is sent to the browser.

  • header(string $header, bool $replace = true, int $response_code = null)
  • $header: The header string to send, e.g., 'Location: https://example.com'
  • $replace: Optional. Whether to replace a previous similar header. Defaults to true.
  • $response_code: Optional. Forces HTTP response code, e.g., 301 for permanent redirect.
php
header('Location: https://example.com');
💻

Example

This example shows how to redirect a user to another page using header(). It sends a Location header and stops script execution with exit().

php
<?php
// Redirect user to example.com
header('Location: https://example.com');
exit();
?>
Output
The browser redirects to https://example.com
⚠️

Common Pitfalls

Common mistakes when using header() include:

  • Sending headers after output (like echo or HTML) causes errors.
  • Not calling exit() after a redirect can lead to unwanted code running.
  • Incorrect header strings cause unexpected behavior.
php
<?php
// Wrong: output sent before header
echo 'Hello';
header('Location: https://example.com'); // Error: headers already sent

// Right: no output before header
header('Location: https://example.com');
exit();
?>
📊

Quick Reference

UsageDescription
header('Location: URL')Redirect browser to another URL
header('Content-Type: type')Set the content type of the response
header('HTTP/1.1 404 Not Found')Send a custom HTTP status code
header('Cache-Control: no-cache')Control browser caching behavior

Key Takeaways

Always call header() before any output to avoid errors.
Use header('Location: URL') to redirect users to another page.
Call exit() after a redirect to stop script execution.
You can send any valid HTTP header string with header().
Use the optional parameters to replace headers or set response codes.