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
- Make a list of pages you allow.
- Check the visitor's choice against the list.
- 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.
Quick recap
- Use
header("Location: ...")followed byexit;. - Put it before any output.
- Never redirect to an address taken straight from the visitor.
- Use an allow list for safety.