How to Make a Redirect in PHP
Redirecting users from one page to another is a common task in web development, and in PHP, it can be easily done using the header() function. Whether you’re redirecting users after form submissions or moving to a new URL, PHP provides a simple way to handle redirects.
In this article, we’ll cover how to make a redirect in PHP using the header() function.
Step 1: Basic Redirect in PHP
The simplest way to redirect a user in PHP is to use the header() function with the Location header. For example:
<?php header("Location: http://example.com/newpage.php"); exit(); ?>
Here’s what happens:
- header(“Location: …”): Sends an HTTP header to the browser, instructing it to redirect to the new URL.
- exit(): Ensures that no further code is executed after the redirect.
Step 2: Using Relative URLs
You can also use relative URLs for redirection. For example:
<?php header("Location: /newpage.php"); exit(); ?>
This will redirect the user to /newpage.php on the same server.
Step 3: Permanent Redirect (301)
If you are permanently moving a page and want search engines to update their records, you can use a 301 redirect:
<?php header("HTTP/1.1 301 Moved Permanently"); header("Location: http://example.com/newpage.php"); exit(); ?>
This tells the browser and search engines that the page has permanently moved to the new location.
Step 4: Conditional Redirects
You can redirect users conditionally based on certain criteria, such as whether they are logged in or not:
<?php if (!isset($_SESSION['user'])) { header("Location: login.php"); exit(); } ?>
In this example, users who are not logged in are redirected to the login page.
Conclusion
Redirects in PHP are simple yet powerful. By using the header() function, you can easily send users to different pages, whether for navigation purposes or permanent page moves. Just remember to always include exit() after the redirect to ensure no further code is executed.