I have a quick question that should be simple for most people here. On a website, I am redirecting all my links through 1 simple PHP redirect called visit.php
I am formatting my outbound redirects like this..
visit.php?url=google.com
visit.php?url=yahoo.com
visit.php?url=aol.com
Then my visit.php looks like this…
<?php
$url = htmlspecialchars($_GET['url']);
if($url == 'google.com'){
header("Location: http://google.com");
}
if($url == 'yahoo.com'){
header("Location: http://yahoo.com");
}
if($url == 'aol.com'){
header("Location: http://aol.com");
}
else {
header("Location: http://mydomain.com/404");
}
The problem I am having is with the else statement. When I delete it from the script, everything works as expected. When I put it in (so any misspellings redirect to a 404) it overrides all the links I defined in the script and redirects to the 404.
Another problem I am having is when the ?url= variable is not used. If a user on my site copies the link to their clipboard and changes it to anything but ?url= I’d like to redirect to the 404. The code I have tried using to accomplish this looks like this…
if(!isset($_GET['url'])){
header("Location: http://mydomain.com/404");
}
My logic is… if the ?url= variable is not set, just redirect to 404 because someone must be playing around. If somebody loads visit.php?id=blah it should just redirect to the 404.
However, I am not getting the expected behavior. I am pretty new to PHP and programming in general… so forgive me if these questions are kindergarten level. Thanks.
You should be using the
if/else if/elseconstruct otherwise that else statement is attached only to the lastif.When the condition of that last
ifis not fulfilled it’ll naturally execute theelseclause.Your initial approach (corrected):
Usual approach:
Best (recommended) approach:
Hmmm… better yet: