To implement HTTP redirection in PHP, you can use the header() function to send the appropriate HTTP headers. The header() function allows you to send custom headers, including the Location header, which is used for redirection. Here are detailed examples of how to implement different types of HTTP redirection in PHP:

 

Redirecting to a URL:

To redirect the user to a different URL, you can set the Location header with the desired URL and specify the appropriate HTTP status code, such as 301 for permanent redirects or 302 for temporary redirects. After setting the header, you can use the exit() or die() function to stop script execution.

// Permanent Redirect (301)
header("HTTP/1.1 301 Moved Permanently");
header("Location: https://www.example.com/new-page");
exit();

// Temporary Redirect (302)
header("HTTP/1.1 302 Found");
header("Location: https://www.example.com/new-page");
exit();

Redirecting with Delay:
If you want to add a delay before the redirection occurs, you can use the sleep() function to pause the script execution for a specified number of seconds before setting the Location header.

// Delayed Redirect (302)
sleep(3); // Delay for 3 seconds
header("HTTP/1.1 302 Found");
header("Location: https://www.example.com/new-page");
exit();

 

Redirecting to the Previous Page:
To redirect the user back to the previous page, you can use the $_SERVER['HTTP_REFERER'] variable to get the referring page and set the Location header accordingly.

if(isset($_SERVER['HTTP_REFERER'])) {
    header("Location: ".$_SERVER['HTTP_REFERER']);
} else {
    header("Location: https://www.example.com");
}
exit();

 

Redirecting with Query Parameters:
If you need to pass query parameters along with the redirection, you can append them to the URL in the Location header.

$id = 123;
$name = "John Doe";
$url = "https://www.example.com/profile?id=".$id."&name=".$name;

header("Location: ".$url);
exit();

 

 

Remember to place the redirection code before any output is sent to the browser, as headers must be sent before any content.

Additionally, it's important to handle redirects securely and validate user input to prevent open redirects or other security vulnerabilities.