The most common and classic way to perform page redirects in PHP is by using the header function. By setting the Location field in the HTTP response header, the browser will automatically redirect to the specified URL. Here is an example:
<?php
header("Location: http://www.example.com");
exit;
?>
It is important to note that no output should be sent before calling the header function, and exit should be called afterward to terminate the script and prevent further code from interfering with the redirect.
Besides server-side header redirects, client-side JavaScript can also be used for page redirects. This method is suitable for certain cases, such as partial page refresh followed by a redirect. Example:
<?php
echo '<script>window.location.href = "http://www.example.com";</script>';
?>
This outputs a JavaScript snippet that causes the browser to redirect when the page loads.
Another redirect method that does not require server support is through HTML meta tags. By setting the page refresh time and target URL, automatic redirection is achieved. Example:
<?php
echo '<meta http-equiv="refresh" content="0;url=http://www.example.com" />';
?>
This method is suitable for automatically redirecting after page content loads but is not recommended for SEO-sensitive pages.
Using appropriate HTTP status codes informs browsers and search engines about the nature of page moves. Commonly used codes are 301 for permanent redirects and 302 for temporary redirects. Example:
<?php
header("HTTP/1.1 302 Found");
header("Location: http://www.example.com");
exit;
?>
Sending the correct status code benefits SEO and user experience.
This article introduced various methods for implementing page redirects in PHP, including the header function, JavaScript, meta refresh, and HTTP status code redirects. Choosing the appropriate method based on your needs can effectively improve website navigation and SEO performance.