Is there anyway to search a textfile for a string?

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
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Is there anyway to search a textfile for a string?

Post 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.
Deemo
Forum Contributor
Posts: 418
Joined: Sun Jan 18, 2004 11:48 am
Location: Washington DC

Post 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()
Last edited by Deemo on Sat Jan 07, 2006 10:08 am, edited 1 time in total.
User avatar
hawleyjr
BeerMod
Posts: 2170
Joined: Tue Jan 13, 2004 4:58 pm
Location: Jax FL & Spokane WA USA

Post by hawleyjr »

How big is the file? Have you thought about putting it into a table?
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

Code: Select all

<?php

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

?>
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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';
Post Reply