简体   繁体   English

从文件中读取IP地址

[英]Read IP address from file

Example 1 例1

<?php
function Piso()
{

  $ip = '77.1.1.1.1';
  $ip2 = $_SERVER['REMOTE_ADDR'];

  return ($ip == $ip2);
}
?>

Example 2 例2

<?php
function Piso()

  {
      $ip = fopen("bune.txt", "r");
      $ip2 = $_SERVER['REMOTE_ADDR'];

      return ($ip == $ip2);
    }
    ?>

I want to read IP address from file bune.txt. 我想从文件bune.txt中读取IP地址。 If i read it == doesnt work. 如果我读它==不起作用。 If i put ip address like example one, it works. 如果我把ip地址放在第一个例子中,那就行了。 But i need example 2 to work. 但我需要示例2来工作。 Example two doesnt work, but i dont know how to read it to can $ip == $ip2. 示例二不起作用,但我不知道如何读取它可以$ ip == $ ip2。 Thanks. 谢谢。

<?php
function Piso()

  {
      $ip = file_get_contents("bune.txt");
      $ip2 = $_SERVER['REMOTE_ADDR'];

      return ($ip == $ip2);
    }
?>

假设文件中只有1个IP地址,则没有其他内容:

$ip = trim(file_get_contents("bune.txt"));

This is because PHP's fopen() function returns a file handle (type resource ) to read (because you passed "r" ) as stream from the file. 这是因为PHP的fopen()函数返回一个文件句柄(类型resource )来读取(因为你传递"r" )作为来自文件的流。

Instead of fopen() use the simple function file_get_contents() which will return the content of the file. 而不是fopen()使用简单的函数file_get_contents() ,它将返回文件的内容。

function Piso() {
    // Absolute path is faster.
    $file = __DIR__ . DIRECTORY_SEPARATOR . "bune.txt";

    // Confirm that the file exists and is readable.
    if (is_readable($file) === false) {
        return false;
    }

    // Use trim() to remove white space and compare read IP against remote address.
    return (trim(file_get_contents($file)) == $_SERVER["REMOTE_ADDR"]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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