Tharindu Kumara Tharindu Kumara - 1 year ago 170
PHP Question

PHP Jump Redirect

I'm trying to redirect users based on the query string on a php file. I created a php file go.php and pasted following code,

if ($v = 'AAAAA') {$link = '';}
if ($v = 'BBBBB') {$link = '';}

header( 'Location: $link' ) ;

I thought I will be able to redirect user to with
But it's not working. The script redirects user to$link
Can anyone help me achieve this? I'm using nginx as webserver with php 7.

Thanks in advance.

Answer Source

You should do something like this

$v = $_GET['V'];
if ($v == 'AAAAA'){
    $link = '';
}elseif ($v == 'BBBBB') {
    $link = '';
   $link = false;  //you could output an error or put a default redirect in here instead.  Then you wouldn't need the second if condition ( with a default redirection )

if( $link ){
  header( "Location: $link" ) ;

A few things to note:

  • You are using assignment = not comparison == in your if condition. In the original both conditions will pass with the end value of $link being the last one ( although its set in the first, the second replace it ), the $v variable will be set to equal BBBBB as well, nither of which is what you want.

  • Variable interpolation ( automatic inserting the value ) only works when using double quotes not single quotes. " $link " vs ' $link ' the first will fill in the value of $link the second will literal be $link as a string.

  • You have no default value if $v is not equal to either condition, what happens?

  • You should us an if elseif because $v cannot be equal to both. In the case it equals the first condition the rest are skipped, performance wise its better but something like that it dosn't matter so much, it's just best practice and more readable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download