How To Redirect With Php

Redirecting a user to another page or URL is a common task in web development. In this blog post, we will learn how to perform a simple redirect using PHP. Redirecting can be useful in multiple scenarios, such as:

  • Redirecting users to a login page when they try to access restricted content.
  • Redirecting users to a success page after they submit a form.
  • Redirecting users to the main page after they log out.

So, let’s dive into the process of redirecting users with PHP.

Using the header() Function

The most common way to redirect users in PHP is by using the header() function. The header() function sends a raw HTTP header to a client. To redirect a user, we need to send the ‘Location’ HTTP header with the URL to which we want to redirect the user.

Here’s an example of how to use the header() function to redirect a user to a different page:

In this example, the user will be redirected to “”. It’s essential to call the exit function after sending the header to terminate the current script. This ensures that no further code is executed after the redirection.

Relative URLs

You might want to redirect users to another page on your own website. In this case, you can use relative URLs to specify the target location. Here’s an example:

In this example, the user will be redirected to the “success.php” page located in the root directory of your website.

Additional Tips

  • Make sure that no output (e.g., HTML or echo statements) is sent to the browser before using the header() function. Doing so will result in a “headers already sent” error.
  • Remember to call the exit function after sending the ‘Location’ header to prevent any further code execution.
  • For security reasons, it’s a good practice to use absolute URLs when redirecting users to external websites.

Now you know how to redirect users with PHP! The header() function is a simple and effective way to achieve this goal. Remember to follow the tips mentioned above to ensure a smooth redirection process.