WebSon
WebSon

Reputation: 521

Print something if ip address exists in file [ php ]

I have some php script that must find if ip address of user exist in txt file and print some text if it's not exist, do nothing.

So i do like this, but something is wrong and i don't know what. Please help. Thank you for help.

<?php

if (!empty($_SERVER["HTTP_CLIENT_IP"])) {$ip = $_SERVER["HTTP_CLIENT_IP"];}
elseif (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {$ip = $_SERVER["HTTP_X_FORWARDED_FOR"];}
else {$ip = $_SERVER["REMOTE_ADDR"];}

$lines = file('http://example.com/ip.txt');

foreach ($lines as $line_num => $line) {
$search_array = array($ip);
    if (array_key_exists($ip,$search_array)){ echo "Hello"; }
    /*else{ echo "not hello";}*/
}

 ?>

ip.txt have lines like this:

178.211.105.33

278.211.115.56

378.451.105.21

271.511.305.01

Upvotes: 1

Views: 658

Answers (2)

mario
mario

Reputation: 145512

This already gets you an array:

$lines = file('http://example.com/ip.txt', FILE_IGNORE_NEW_LINES);

There's no need to loop over it.
You can just use in_array right away:

$found = in_array($ip, $lines);

You might want to use preg_grep() if there's any formatting or linebreak variance in the file however.

Upvotes: 2

WebSon
WebSon

Reputation: 521

I find and fix my error..

in line

$search_array = array($ip); //-- that was error - $ip
if (array_key_exists($ip, $search_array)){ echo "Hello"; }  
//-- that was error - "array_key_exists"

 $search_array = array($line); //-- error fixed by this
 if (in_array($ip, $search_array)){ echo "Hello"; } 
 //-- thanx to @mario for using "in_array" against "array_key_exists"

Upvotes: 0

Related Questions