Page 1 of 1

Is there anyway to search a textfile for a string?

Posted: Sat Jan 07, 2006 10:01 am
by kaisellgren
I have IPs.txt and I want to search if user's IP is banned? How to search? I have spent about 40minutes browsing the php.net doc, but can't find.

Posted: Sat Jan 07, 2006 10:07 am
by Deemo
assuming that each IP address is on a seperate line:

Code: Select all

$search = "73.13.24.124"    //What you are searching for
$lines = file("IPs.txt");
foreach ($lines as $value)
{
  if ($search == $value)
    //there is a match
}
file()

Also, if they are not seperated by lines you can do file_get_contents() and then explode()

Posted: Sat Jan 07, 2006 10:08 am
by hawleyjr
How big is the file? Have you thought about putting it into a table?

Posted: Sat Jan 07, 2006 10:10 am
by Jenk

Code: Select all

<?php

if (in_array($ip, file('IPs.txt')) {
    echo 'You are banned!';
}

?>

Posted: Sat Jan 07, 2006 12:42 pm
by Chris Corbyn
I'm not sure that you might actually need to use trim() with file() since it will contain the \n at the end of the line.

I'd do it with a combination of file_get_contents() and strpos()

Code: Select all

$data = file_get_contents('ip.txt');
if (strpos($ip, $data) !== false) echo 'Banned User';