user3307783
user3307783

Reputation: 157

Read IP address from file

Example 1

<?php
function Piso()
{

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

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

Example 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. If i read it == doesnt work. If i put ip address like example one, it works. But i need example 2 to work. Example two doesnt work, but i dont know how to read it to can $ip == $ip2. Thanks.

Upvotes: 2

Views: 1136

Answers (3)

Fleshgrinder
Fleshgrinder

Reputation: 16253

This is because PHP's fopen() function returns a file handle (type resource) to read (because you passed "r") as stream from the file.

Instead of fopen() use the simple function file_get_contents() which will return the content of the file.

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"]);
}

Upvotes: 3

AbraCadaver
AbraCadaver

Reputation: 78994

Assuming there is only 1 IP address and nothing else in the file:

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

Upvotes: 3

Egor Sazanovich
Egor Sazanovich

Reputation: 5089

<?php
function Piso()

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

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

Upvotes: 5

Related Questions