Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to make a safe PHP redirect

A redirect sends a visitor from one page to another. This guide shows how to do it in PHP without opening a security hole.

Web Hosting2 min read3 steps

What is a redirect?

A redirect is like a "we moved" sign on a shop door. The browser asks for one page and the server says, "Go to this other address instead."

The basic method

PHP sends a message called a header. A header is a hidden note sent before the page itself. The Location header holds the new address.

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

This sends visitors to the new page. The number 301 means "moved for good". Use 302 for a short-term move.

Rule 1: Always call exit

Without exit, PHP keeps running the rest of the file. Private content could still be processed. Always stop right after the redirect.

Rule 2: Send nothing before the header

Headers must go first. If any text, space or HTML is printed before, you get "headers already sent". Put the redirect at the very top of the file.

Rule 3: Never trust the address from a visitor

Do not do this:

header("Location: " . $_GET['url']);

A bad person can send your visitors to a fake site through your link. This is called an open redirect. Use a safe list of allowed places instead.

A safe example

  1. Make a list of pages you allow.
  2. Check the visitor's choice against the list.
  3. Redirect only if it matches. Otherwise go to a default page.
<?php
$allowed = [
  "home" => "/index.php",
  "shop" => "/shop.php"
];
$key = $_GET['page'] ?? 'home';
$target = $allowed[$key] ?? "/index.php";
header("Location: " . $target, true, 302);
exit;
?>

The visitor can only pick a name. Your code picks the real address.

Other tips

  • Use a full address when sending visitors to another site.
  • Use 301 only when the move is permanent. Search engines remember it.
  • Do not use JavaScript or meta refresh as your main method. Headers are cleaner.
Tip: Test redirects in a private browser window. Browsers remember 301 moves and can hide your changes.

Quick recap

  • Use header("Location: ...") followed by exit;.
  • Put it before any output.
  • Never redirect to an address taken straight from the visitor.
  • Use an allow list for safety.