PHP Code to Redirect with 302 and a Referer


Some server URLs (images or videos) are protected with the referer link checks, so you cannot directly use the URLs by placing them in your website HTMLs. You will get 403 forbidden error, don’t have permission to access url on this server. The Server shows Error: Denied by referer ACL.

You can’t directly modify the referer in the client, in your HTML hyper link tag aka A, or using Javascript with Ajax. However, there is a workaround, which is to by pass this using 302 redirect and a Referer:

Redirect URL with 302 and a Referer

To perform a PHP redirect with a 302 status code and include the referer header, you can use the following code:

1
2
3
4
5
6
<?php
$referer = $_SERVER['HTTP_REFERER'];
header("Location: http://example.com/new-page.php", true, 302);
header("Referer: $referer");
exit();
?>
<?php
$referer = $_SERVER['HTTP_REFERER'];
header("Location: http://example.com/new-page.php", true, 302);
header("Referer: $referer");
exit();
?>

In this code, the $_SERVER[‘HTTP_REFERER’] variable retrieves the referer URL from the request headers. The header() function is then used to set the redirect location with the Location header, the HTTP status code 302, and the Referer header with the previously obtained referer value. Finally, the exit() function is called to terminate the script execution.

Note that the Referer header may not be present in all requests, as it depends on the client’s behavior. Therefore, you should handle cases where the referer header is not available or empty.

And, we can modify this to suit our needs, for example, you can pass the URL to redirect, and the referer in query string parameter url and referer respectively.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
    $url = $_GET["url"] ?? "";
    if (!$url) {
        echo "url parameter needs to be set."
        exit();
    }
    $referer = $_GET["referer"] ?? "";
    if (!$referer) {
        $referer = $_SERVER['HTTP_REFERER'];
    }
    header("Location: $url", true, 302);
    header("Referer: $referer");
    exit();
?>
<?php
    $url = $_GET["url"] ?? "";
    if (!$url) {
        echo "url parameter needs to be set."
        exit();
    }
    $referer = $_GET["referer"] ?? "";
    if (!$referer) {
        $referer = $_SERVER['HTTP_REFERER'];
    }
    header("Location: $url", true, 302);
    header("Referer: $referer");
    exit();
?>

This should by pass the Denied by referer ACL error.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
412 words
Last Post: NodeJs code to check the balance of a BTS account (BitShares Blockchain)
Next Post: Teaching Kids Programming - Algorithms to Find Neither Minimum nor Maximum

The Permanent URL is: PHP Code to Redirect with 302 and a Referer

Leave a Reply