0

How do I create a PHP script that will redirect to a custom URL when link added in the URL. For instance, when a user visits this:

http://example.com/link.php?r=http://www.google.com

It should redirect them instantly to google.

Ideally, is it possible to ensure that the click itself came locally?

So far, I have this:

$url = "http://example.com";
$domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));
$refDomain = str_ireplace('www.', '', parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST));

if(strcmp($domain, $refDomain) == 0) {
     header("Location:".$_GET['r']);
}

I've added the link.php file but it doesn't redirect. It may be because the file is located in the root folder of a WordPress install, but I don't think that should stop it from working.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155

3 Answers3

0

try to use java-script to solve the redirection issues,

print ("<script>window.location.href=".$_GET['r'].";</script>");
0

Try adding a space after Location as in shown below. I feel exit is missing. Or you can also use die.

header("Location: ".$_GET['r']);
exit();
//OR
die();

Redirect URL in PHP

Community
  • 1
  • 1
LearningToCode
  • 631
  • 1
  • 12
  • 23
0

This seems to work every time. Am I missing something?

<?php
if ( $_SERVER["REQUEST_METHOD"] == 'GET' && isset( $_GET['r'])) {
    $url = "http://example.com";
    $domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));
    $refDomain = str_ireplace('www.', '', parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST));

    if(strcmp($domain, $refDomain) == 0) {
        header("Location: {$_GET['r']}");
        exit;
    }
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149