首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP检查文件是否包含字符串

PHP检查文件是否包含字符串
EN

Stack Overflow用户
提问于 2012-01-30 11:33:04
回答 6查看 105K关注 0票数 41

我正在尝试查看文件是否包含发送到页面的字符串。我不确定这段代码出了什么问题:

代码语言:javascript
复制
?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
}
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2012-01-30 11:36:18

简单得多:

代码语言:javascript
复制
<?php
    if( strpos(file_get_contents("./uuids.txt"),$_GET['id']) !== false) {
        // do stuff
    }
?>

在回应关于内存使用的评论时:

代码语言:javascript
复制
<?php
    if( exec('grep '.escapeshellarg($_GET['id']).' ./uuids.txt')) {
        // do stuff
    }
?>
票数 93
EN

Stack Overflow用户

发布于 2012-01-30 11:40:57

is代码在搜索较大的文件时效率更高。

代码语言:javascript
复制
$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);
票数 24
EN

Stack Overflow用户

发布于 2015-12-10 00:08:30

代码语言:javascript
复制
function getDirContents($dir, &$results = array())
{

    if ($_POST['search'] == null)
        exit;

    ini_set('max_execution_time', $_POST['maxtime']);

    $_SESSION['searchString'] = $_POST['search'];

    echo "<script>var elm = document.getElementById('search');elm.value='$_POST[search]';</script>";

    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 . "<br>";
            }
            $results[] = $path;
        } else if ($value != "." && $value != "..") {
            getDirContents($path, $results);
            $results[] = $path;
        }
    }
    return $results;
}

原始项目:https://github.com/skfaisal93/AnyWhereInFiles

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9059026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档