Is there anyway to search a textfile for a string?
Moderator: General Moderators
- 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?
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.
assuming that each IP address is on a seperate line:
file()
Also, if they are not seperated by lines you can do file_get_contents() and then explode()
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
}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.
Code: Select all
<?php
if (in_array($ip, file('IPs.txt')) {
echo 'You are banned!';
}
?>- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
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()
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';