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?

1
  • 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" Commented Oct 21, 2017 at 6:00

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, it worked. I also noticed it after few mins but you were really quick to answer.
SO requires 10 mins wait before accepting the answer. :)
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']?

3 Comments

Thanks for showing alternative way by using $_SERVER. BTW, which is the better, secure and faster way to go.
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
Also, your first method have a syntax error, 'Location:' $_GET['link'] should be 'Location:' . $_GET['link']
1
$url = !empty($_GET['link']) ? $_GET['link'] : '';
if ($url){
    header('Location:' . $url);
    exit;
}else{
    echo 'invalid link';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.