Redirect if User's IP Address is in .txt file

时间:2016-10-20 19:02:09

标签: php if-statement

I have tried REMOTE_ADDR and also HTTP_X_FORWARDED_FOR but im still having issues getting this to work.

Basically, if the users IP is found in the text file I want the user to be redirected to cnn.com, if no IP then redirected to google.com

Here is the code that isn't working with my IP in the file:

<?php

$iplist = @file("ip.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$iparray = in_array($_SERVER["HTTP_X_FORWARDED_FOR"], $iplist);
//$iparray = in_array($_SERVER["REMOTE_ADDR"], $iplist);

//###if ?test= is not empty
if (!empty($_GET["test"])){
        if($iparray){
            header("Location: http://cnn.com");die;
        }
}
header("Location: http://google.com");

?>

Note: I do have ?test=1 at the end of my URL when testing

I would like to keep the format of just keeping the if statement + stopping the rest of code from executing if possible so header("Location: http://google.com"); does not execute.

1 个答案:

答案 0 :(得分:0)

If your ip is in the file and the filepath is correct, try this:

if (false !== strpos(file_get_contents($filename), $ip_to_search)){
     // ip in the file
}
else {
     // otherwise
}