How to make a redirect in PHP?


In PHP, there are several ways to make a redirect. Here are some of the most common methods:

  • Using the header() function: The header() function is used to send a raw HTTP header to the client. By using this function, we can send a redirect header to the browser, which will then redirect the user to the specified URL. Here's an example:
<?php
header("Location: http://www.example.com/");
exit;
?>

In this example, we're using the header() function to send a "Location" header to the browser, which tells it to redirect to the specified URL. The "exit" statement is used to stop the script from executing any further.

  • Using the meta refresh tag: Another way to redirect in PHP is by using the meta refresh tag in HTML. This method is not recommended for permanent redirects, as it can cause issues with search engine optimization. Here's an example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="0; URL='http://www.example.com/'" />
</head>
<body>
</body>
</html>

In this example, we're using the meta refresh tag to redirect the user to the specified URL after 0 seconds.

  • Using the JavaScript location object: We can also use JavaScript to redirect the user to a different URL. Here's an example:
<!DOCTYPE html>
<html>
<head>
<script>
window.location.replace("http://www.example.com/");
</script>
</head>
<body>
</body>
</html>

In this example, we're using the JavaScript location object to redirect the user to the specified URL.

Note: When using any of these methods, it's important to make sure that there is no output sent to the browser before the redirect header is sent. Otherwise, the redirect may not work as expected.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.