Sometimes you need to redirect a user to a different page — for example, after a successful login, or when a page has moved. PHP's built-in header() function handles both 301 permanent and 302 temporary redirects.
301 Permanent Redirect
A 301 redirect tells search engines and browsers that a page has moved permanently to a new URL. Search engines transfer link equity to the new URL.
<?php
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.example.com/new-page");
exit();
?>
302 Temporary Redirect
A 302 redirect tells browsers to go to a different URL temporarily. Search engines keep the original URL indexed and do not transfer link equity.
<?php
header("Location: http://www.example.com/temporary-page");
exit();
?>
Note: Omitting the HTTP/1.1 301 header results in a 302 temporary redirect by default. Use 301 redirects wherever possible — they are more search-engine friendly and preserve your page's ranking signals.
Important Rules
header()must be called before any HTML or whitespace is sent to the browser.- Always follow a
header("Location: ...")call withexit()to stop script execution immediately.
Hope this tutorial is useful for you. Keep following PHP Tutorial for Beginners for more help.