I've been scratching my head on the best way to accomplish this.
I'm getting 8 variables from a url: a=imagine b=lead c=champion d=champion e=champion f=champion g=lead h=champion
In this example there's 5 "champion" so I'd redirect to my champion page.
I've added them into an array:
$a = $_GET["a"]; $b = $_GET["b"]; $c = $_GET["c"]; $d = $_GET["d"]; $e = $_GET["e"]; $r = $_GET["r"]; $g = $_GET["g"]; $h = $_GET["h"];
$info = array($a,$b,$c,$d,$e,$f,$g,$h); print_r(array_count_values($info));
and then printed: Array ( [imagine] => 1 [lead] => 2 [champion] => 5 )
Am I doing it right? How can I use those values to redirect to my champion page as that's the highest count?
CodePudding user response:
If I understand you correctly:
$list = ['imagine' => 1 ,'lead' => 2, 'champion' => 5 ];
// find the highest count
$highest = max($list);
// check what page it is
foreach($list as $page=>$count){
// redirect
if($count === $highest){
header('Location: ' . $page);
exit();
}
}
Beware that relying on the user input is not safe. I'd also look up a white list for the pages.
CodePudding user response:
First, I agree that array_count_values
is a good tool for this, but you don't need to make a new array with all the $a
, $b
, etc. variables. You can just do
$info = array_count_values($_GET);
After you have that, you can sort the array in descending order and take the first key to find the page you want to redirect to.
arsort($info);
$location = key($info);
I agree with the other answer that redirecting to a page based on user input is risky, and you should not redirect without first verifying that the location is valid. If you only have a few valid locations, this could be as simple as:
if (in_array($location, ['champion', 'lead', 'imagine'])) {
header("Location: yourdomain/$location");
}