Looking for a function to find a string in a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Daisy Cutter
Forum Commoner
Posts: 75
Joined: Sun Aug 01, 2004 9:51 am

Looking for a function to find a string in a file

Post by Daisy Cutter »

I am trying to make a blocklist for my site, and I've got a text file with several IPs seperated by a newline. I would like to use a function that returns either TRUE if the string (the IP) is found in the file, or FALSE if it is not.

Thanks!
User avatar
trukfixer
Forum Contributor
Posts: 174
Joined: Fri May 21, 2004 3:14 pm
Location: Miami, Florida, USA

Post by trukfixer »

Code: Select all

$target = $_SERVER['REMOTE_ADDR'];
$string = file_get_contents('/var/www/whatever/your_ip_file.txt');
$iparr = explode('\n',$string);
if(in_array($target,$ip_arr));
{
    $test = true;
}
else
{
   $test = false;
}
foobar
Forum Regular
Posts: 613
Joined: Wed Sep 28, 2005 10:08 am

Post by foobar »

Yay for the PHP Manual. The besterest resource on the net!
Daisy Cutter
Forum Commoner
Posts: 75
Joined: Sun Aug 01, 2004 9:51 am

Post by Daisy Cutter »

trukfixer wrote:

Code: Select all

$target = $_SERVER['REMOTE_ADDR'];
$string = file_get_contents('/var/www/whatever/your_ip_file.txt');
$iparr = explode('\n',$string);
if(in_array($target,$ip_arr));
{
    $test = true;
}
else
{
   $test = false;
}
Thanks a lot! That does it's job well. :D

I guess I was looking for the wrong thing, I was in the PHP manual looking for preg_match and stuff.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Code: Select all

$string = file_get_contents('/var/www/whatever/your_ip_file.txt');
$iparr = explode('\n',$string);
The shortcut is to use file.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post by josh »

The efficient way is to use fgets()
Post Reply