Redirection in PHP

The header function in PHP can be used to redirect the user from one page to another. It is an in-built function that sends raw HTTP header to the destination (client).

Syntax

header($header_value, $replace_value, $http_response_code)

Parameters

  • header_value − The header string to be sent
  • replace_value − Optional boolean that indicates whether to replace a previous similar header (default: true)
  • http_response_code − Optional HTTP response code (default: 302 for redirects)

Basic Redirection Example

Here's how to redirect to another website −

<?php
   header("Location: /tutorials/index.htm");
   exit;
?>

The exit statement is crucial to prevent further code execution after the redirect.

Redirection with HTTP Status Code

You can specify different HTTP status codes for various types of redirects −

<?php
   // Permanent redirect (301)
   header("Location: /new-page.php", true, 301);
   exit;
?>

Common Redirect Types

Status Code Type Use Case
301 Permanent Redirect Page moved permanently
302 Temporary Redirect Temporary page change
303 See Other After form submission

Important Notes

  • Headers must be sent before any output (HTML, whitespace, etc.)
  • Always use exit or die() after redirect to stop script execution
  • Use relative URLs when redirecting within the same domain

Conclusion

The header() function is essential for page redirection in PHP. Remember to use appropriate status codes and always call exit after redirection to ensure proper functionality.

Updated on: 2026-03-15T09:01:34+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements