访问页面时重定向特定的IP地址

时间:2018-04-03 04:18:02

标签: php

任何人都可以帮我解决这个问题吗?我在访问网页时试图重定向特定的IP地址(存在于ips.txt中)。

代码:

<?php
ob_start(); //first line

// get the visitor ip.
if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ipaddress = $_SERVER['HTTP_CLIENT_IP']."\r\n";
    }
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check if ip is pass from proxy
    {
      $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']."\r\n";
    }
else
    {
      $ipaddress = $_SERVER['REMOTE_ADDR']."\r\n";
    }


// check if the visitor ip exists in the txt file
$s = file_get_contents('ips.txt');
$pos = strpbrk($ipaddress, $s);

if ($pos === false) {
    // If it doesn't exist, record the IP in the txt file and then switch to an external page
    $ips = fopen("ips.txt", "a");
    fwrite($ips, $ipaddress . "\n");
    header("Location: https://google.com/");
} else {
    // If it exists, do nothing or switch to an external page
    header("Location: https://example.com"); 
}
?>

1 个答案:

答案 0 :(得分:0)

$s = file_get_contents("ips.txt");
if(strpos($ipaddress, $s) !== false){
// IP exists
}