0

I am trying to write a simple PHP URL redirect script but it's not working.

    <?php

    if (isset($_GET['link'])) {
header('Location: $_GET['link']');    
    }else{
        echo 'invalid link';
    }
?>

If I access the script as http://www.example.com/redirect.php, then it goes into else loop and I get output as 'invalid link' in the browser.

But if I access it as https://www.example.com/redirect.php?link=https://www.google.com then I get HTTP error 500. Ideally page should be redirected to https://www.google.com

I am new to PHP and unable to figure it out, any help please?

Pankaj
  • 5,132
  • 3
  • 28
  • 37
  • just saw php error log "[21-Oct-2017 05:53:48 UTC] PHP Parse error: syntax error, unexpected 'link' (T_STRING), expecting ',' or ')' in redirect.php on line 4" – Pankaj Oct 21 '17 at 06:00

3 Answers3

1

try the following:

if (isset($_GET['link'])) {
    header("Location: {$_GET[link]}");    
}else{
    echo 'invalid link';
}

' single quotes cannot escape variables in php you need to use " double quotes for that. And there is not need to enclose the index with quotes when being used inside a string. And as for the {} curly brackets that I am using look into Complex Curly Brackets

Also, as you were doing it with 'Location: $_GET['link']' there was another problem with that, that the string was starting from 'Location: but was ending at $_GET[' because it was closing the single quotes there and was causing an error too.

mega6382
  • 9,211
  • 17
  • 48
  • 69
1

you are giving invalid string matching string

if (isset($_GET['link'])) {
header('Location:'.$_GET['link']);    
    }else{
        echo 'invalid link';
    }

or this method also works

header("Location: " . $_SERVER['REQUEST_URI']);

see the difference $_GET['link'] and $_SERVER['REQUEST_URI']

what is the difference between $_SERVER['REQUEST_URI'] and $_GET['q']?

jvk
  • 2,133
  • 3
  • 19
  • 28
  • Thanks for showing alternative way by using $_SERVER. BTW, which is the better, secure and faster way to go. – Pankaj Oct 21 '17 at 06:10
  • Security and speed wise there is no difference as the alternative method only uses another variable. But it will not provide the same result. It will work for `https://www.example.com/redirect.php?link=test.php` but not for `https://www.example.com/redirect.php?link=https://www.google.com` – mega6382 Oct 21 '17 at 06:15
  • Also, your first method have a syntax error, `'Location:' $_GET['link']` should be `'Location:' . $_GET['link']` – mega6382 Oct 21 '17 at 06:20
1
$url = !empty($_GET['link']) ? $_GET['link'] : '';
if ($url){
    header('Location:' . $url);
    exit;
}else{
    echo 'invalid link';
}
Nimesh Vagadiya
  • 602
  • 3
  • 8
  • 18