【问题标题】:PHP check if file contains a stringPHP 检查文件是否包含字符串
【发布时间】:2012-02-21 23:04:00
【问题描述】:

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

?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
}

【问题讨论】:

  • 如果你var_dump($buffer, $id);而不是通过if比较它们呢?
  • 如有错误请指出。

标签: php fopen strpos


【解决方案1】:

简单得多:

<?php
    if( strpos(file_get_contents("./uuids.txt"),$_GET['id']) !== false) {
        // do stuff
    }
?>

针对内存使用的cmets:

<?php
    if( exec('grep '.escapeshellarg($_GET['id']).' ./uuids.txt')) {
        // do stuff
    }
?>

【讨论】:

  • 更简单但更消耗内存
  • 不必将整个文本加载到内存中。
  • @zerkms 现在怎么样?
  • @响应 cmets 关于内存使用不适合我的问题
  • @nyedidikeke 当然,创建一个包含 10 个字符串的文件,应用该代码,它将丢失第一个字符串和最后一个字符串。
【解决方案2】:

搜索较大文件时,is 代码更高效。

$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);

【讨论】:

  • ps,more efficient,他的意思是probably slower (unless file_get_contents use so much ram that you start swapping, in which case this might be faster), but should use significantly less ram,同时警告,此算法不适用于查找包含换行符的字符串,除非唯一的换行符位于字符串的末尾,请保持记住这一点:)
  • 他确实说过“更大的文件”,如果文件变得非常大(比如最近发布的具有非常多密码哈希的文件),可能很容易达到内存限制
【解决方案3】:
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】:

    这是有效的,我已经测试了端到端。

    <?php
    // incoming record id 
    // checking in uuids.txt file
    if (exec('cat ./uuids.txt | grep '.escapeshellarg($_GET['id']))) {
         // do stuff
         echo 'found...';
    } 
    ?>
    

    【讨论】:

      【解决方案5】:
      <?php
          function getDirContents($dir, &$results = array()){
              $files = scandir($dir);
              foreach($files as $key => $value){
                  $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
                  if(!is_dir($path)) {
                      $results[] = $path;
                  } else if($value != "." && $value != "..") {
                      getDirContents($path, $results);
                      $results[] = $path;
                  }
              }
              return $results;
          }
          $res = getDirContents('path');
          $searchfor = 'search string';
          foreach ($res as $file) {
              if(is_dir($file)) {}else{
                  $contents = file_get_contents($file);
                  $pattern = preg_quote($searchfor, '/');
                  $pattern = "/^.*$pattern.*\$/m";
                  if(preg_match_all($pattern, $contents, $matches)){ ?>
                      <tr>
                          <td> <?php $string = implode("\n", $matches[0]); echo str_replace($searchfor,'<strong style="background-color:#ffff00">'.$searchfor.'</strong>',$string); ?> </td>
                          <td> <?php echo  $file; ?> </td>
                      </tr>
                  <?php }else{
                      //echo "No matches found";
                  }
              }
          }
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-01-14
        • 2012-06-23
        • 1970-01-01
        • 2021-09-15
        • 1970-01-01
        • 2014-03-03
        • 1970-01-01
        • 2014-07-25
        • 2015-04-11
        相关资源
        最近更新 更多