1

i have a problem i couldn't figure out since im self-taught and still exploring the php world

so i have a text file that looks like this:

951753159
456787541
123156488
748651651

and i got an url with a variable

http://example.com/mypage.php?variable=951753159

what i want is to check if the url variable matches one of the txt file lines in order to execute a code

i already tried this

 $search = $_GET["variable"];
 $file = "variables.txt";
 if (preg_match('/^' . $search . '$/m', file_get_contents($file))) { 
 THE CODE THAT I WANT TO EXECUTE
 }

but for some reason it matches the whole content of the file

any help is highly appreciated

Thanks in advance :)

unxio
  • 11
  • 2
  • 2
    Possible duplicate of [How to read a file line by line in php](http://stackoverflow.com/questions/13246597/how-to-read-a-file-line-by-line-in-php) – David Nov 17 '15 at 16:57
  • Maybe this could help you (possible repost) : http://stackoverflow.com/questions/3686177/php-to-search-within-txt-file-and-echo-the-whole-line – SamyQc Nov 17 '15 at 16:57

4 Answers4

1

Try with an array from file():

$lines = file("variables.txt", FILE_IGNORE_NEW_LINES);

if(in_array($_GET["variable"], $lines)) {
    // YES FOUND
} else {
    // NOT FOUND
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
0

From the documentation on `file_get_contents', the entire contents of the file are read as a string. So that is why it is matching against the entire file.

The command that you want to use is file, this reads the file into an array of each line.

Schleis
  • 41,516
  • 7
  • 68
  • 87
0

I would

Use file to read the file into an array.

Then array_flip the array so that it's values are now the keys

Which allows me to isset($array[$key])

Dale
  • 10,384
  • 21
  • 34
0

You can do this.

<?php
#$search = $_GET["variable"];
$search = '123156488';
$file_txt = "content.txt";
$file = file($file_txt);//convert the txt in array
foreach ($file as $key => $value) {
    if (trim($search) == trim($value)) {
        print "DO something! " . $value;
    }
}?>

Regards. Nelson.

nguaman
  • 925
  • 1
  • 9
  • 23