Effective file search in PHP

I would like to save from 0 to ~ 5000 IP addresses in a text file with an unbound header at the top. Something like that:

Unrelated data
Unrelated data
----SEPARATOR----
1.2.3.4
5.6.7.8
9.1.2.3

Now I would like to find if "5.6.7.8" is in this text file using PHP. I only ever downloaded the whole file and processed it in memory, but I wondered if there was a more efficient way to search for a text file in PHP. I only need true / false if it is there.

Can anyone shed some light? Or would I be stuck with downloading in the whole file first?

Thanks in advance!

+3
source share
7 answers

5000 is not many records. You can easily do this:

$addresses = explode("\n", file_get_contents('filename.txt'));

and do a manual search and it will be fast.

, , . 5000 , .

, . .

+5

, perl , - :

<?php
...
$result = system("perl -p -i -e '5\.6\.7\.8' yourfile.txt");
if ($result)
    ....
else
    ....
...
?>

- IP- :

# 1.2.txt
1.2.3.4
1.2.3.5
1.2.3.6
...

# 5.6.txt
5.6.7.8
5.6.7.9
5.6.7.10
...

... etc.

, , , , .

+1

grep .

0

fgets()

. , . , IP , , IP , , .

0

GREP backticks Linux. - :

$searchFor = '5.6.7.8';
$file      = '/path/to/file.txt';

$grepCmd   = `grep $searchFor $file`;
echo $grepCmd;
0

, PHP , :

http://www.php.net/manual/en/function.fgets.php#59393

//File to be opened
$file = "huge.file";
//Open file (DON'T USE a+ pointer will be wrong!)
$fp = fopen($file, 'r');
//Read 16meg chunks
$read = 16777216;
//\n Marker
$part = 0;

while(!feof($fp)) {
    $rbuf = fread($fp, $read);
    for($i=$read;$i > 0 || $n == chr(10);$i--) {
        $n=substr($rbuf, $i, 1);
        if($n == chr(10))break;
        //If we are at the end of the file, just grab the rest and stop loop
        elseif(feof($fp)) {
            $i = $read;
            $buf = substr($rbuf, 0, $i+1);
            break;
        }
    }
    //This is the buffer we want to do stuff with, maybe thow to a function?
    $buf = substr($rbuf, 0, $i+1);
    //Point marker back to last \n point
    $part = ftell($fp)-($read-($i+1));
    fseek($fp, $part);
}
fclose($fp);

: hackajar yahoo com

0

Are you trying to compare the current IP address with the text files listed in the IP list? unrelated data will not match. so just use strpos on the full contents of the file (file_get_contents).

<?php
    $file = file_get_contents('data.txt');
    $pos = strpos($file, $_SERVER['REMOTE_ADDR']);
    if($pos === false) {
        echo "no match for $_SERVER[REMOTE_ADDR]";
    }
    else {
        echo "match for $_SERVER[REMOTE_ADDR]!";
    }
?>
0
source

Source: https://habr.com/ru/post/1715641/


All Articles