How to make a redirect on php

Learn how to create a redirect with PHP, including an example of a 301 redirect.

Creating a Redirect with PHP

A redirect is a way of sending visitors from one page to another on a website. It can be used for a variety of purposes, such as when a web page has moved to a new address, when a user is logged out of a protected area, or when a website is still in development.

In this tutorial, we'll be looking at how to create a redirect using PHP. We'll be using the header() function to do this, which takes two arguments. The first argument is the redirection type, and the second is the URL of the page we want to redirect to.


// Redirect to example.com
header("Location: http://example.com");

// Redirect to example.com/page
header("Location: http://example.com/page");

// Redirect and set status code to 301 (permanent redirect)
header("Location: http://example.com", true, 301);

The header() function will send an HTTP header to the browser, which tells it to redirect to the URL specified. This will cause the browser to navigate to the new page automatically.

We can also set the status code in the header to indicate the type of redirect. The most common status codes for redirects are 301 (permanent) and 302 (temporary). We can set the status code using the third argument of the header() function.

It's important to note that the header() function must be called before any output is sent to the browser. If any output (such as an HTML page or an error message) is sent before the header() function is called, the redirect will not work.

Once we've set up the redirect, it will take effect immediately and the user will be redirected to the new page. This is the simplest and best way to create a redirect using PHP.

Answers (0)