简体   繁体   中英

PHP redirect not working (based on user agent string)

I am running the following redirect script:

<?php
$badAgents = array('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0');
if(in_array($_SERVER['HTTP_USER_AGENT'],$badAgents)) {
require("1.php");
} else {
require("2.php");
}
?>

However every single visitor is getting sent to "2.php" regardless of their user agent. For example I go in Firefox, I got to 2.php, I go in Internet Explorer, I see 2.php.

Please may someone direct me as to what I'm doing wrong?

Thank you for your time

Check our logic.

Here's the pseudo logic you are using:

  • If the user has a bad user agent, then require 1.php.
  • If the user does NOT have a bad user agent, then require 2.php.

Unless the user visits your page with exactly the right version of Firefox, the code you're using will not use 1.php.

I would also recommend you change your code as follows:

if (stripos($_SERVER['HTTP_USER_AGENT'], 'firefox') === false) {
    require '2.php';
} else {
    require '1.php';
}

Your String is a bit to long to match. It's better when you only filter for a short but explicit string like Firefox .

<?php
if(stripos($_SERVER['HTTP_USER_AGENT'], 'firefox') !== false)) {
    require("1.php");
} else {
    require("2.php");
}
?>

Then your change is bigger that the "rule" match.

The second is that there are some functions to parse the User agent like get_browser and you get a better result to work with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM