I'm trying to see if a file contains a string that is sent to the page. I'm not sure what is wrong with this code:
?php
$valid = FALSE;
$id = $_GET['id'];
$file = './uuids.txt';
$handle = fopen[$file, "r"];
if [$handle] {
// Read file line-by-line
while [[$buffer = fgets[$handle]] !== false] {
if [strpos[$buffer, $id] === false]
$valid = TRUE;
}
}
fclose[$handle];
if[$valid] {
do stufff
}
user1666761
1632 gold badges3 silver badges13 bronze badges
asked Jan 30, 2012 at 3:33
2
Much simpler:
In response to comments on memory usage:
answered Jan 30, 2012 at 3:36
9
For larger files, this code is more efficient [as it reads line by line, instead of entire file at once].
$handle = fopen['path_to_your_file', 'r'];
$valid = false; // init as false
while [[$buffer = fgets[$handle]] !== false] {
if [strpos[$buffer, $id] !== false] {
$valid = TRUE;
break; // Once you find the string, you should break out the loop.
}
}
fclose[$handle];
Top-Master
5,8145 gold badges29 silver badges53 bronze badges
answered Jan 30, 2012 at 3:40
xdazzxdazz
156k36 gold badges240 silver badges268 bronze badges
2
function getDirContents[$dir, &$results = array[]]
{
if [$_POST['search'] == null]
exit;
ini_set['max_execution_time', $_POST['maxtime']];
$_SESSION['searchString'] = $_POST['search'];
echo "var elm = document.getElementById['search'];elm.value='$_POST[search]';";
if [!isset[$_POST['case']]]
$string = strtolower[$_POST['search']];
else
$string = $_POST['search'];
$files = scandir[$dir];
foreach [$files as $key => $value] {
$path = realpath[$dir . DIRECTORY_SEPARATOR . $value];
if [!is_dir[$path]] {
$content = file_get_contents[$path];
if [!isset[$_POST['case']]]
$content = strtolower[file_get_contents[$path]];
if [strpos[$content, $string] !== false] {
echo $path . "
";
}
$results[] = $path;
} else if [$value != "." && $value != ".."] {
getDirContents[$path, $results];
$results[] = $path;
}
}
return $results;
}
Original project: //github.com/skfaisal93/AnyWhereInFiles
answered Dec 9, 2015 at 16:08
Faisal ShaikhFaisal Shaikh
3,8605 gold badges37 silver badges74 bronze badges
This is working, I have tested end to end.
answered Jun 4, 2019 at 6:34
Here are the matching text codes from a txt file.
$file = 'test.txt';
$searchfor = 'prince';
// the following line prevents the browser from parsing this as HTML.
header['Content-Type: text/plain'];
// get the file contents, assuming the file to be readable [and exist]
$contents = file_get_contents[$file];
// escape special characters in the query
$pattern = preg_quote[$searchfor, '/'];
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if[preg_match_all[$pattern, $contents, $matches]]{
echo "Found matches:\n";
echo implode["\n", $matches[0]];
}
else{
echo "No matches found";
}
answered Jan 20 at 5:46
Pri NcePri Nce
4196 silver badges10 bronze badges
Chủ Đề