简体   繁体   中英

PHP Validate Value $_GET from url against lines of a txt file

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 :)

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
}

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.

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])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM