2012-01-30 106 views
22

我試圖查看一個文件是否包含發送到頁面的字符串。我不知道什麼是錯,此代碼:PHP檢查文件是否包含字符串

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

如果你'的var_dump($緩衝區,$ ID);'而不是用'if'比較它們? – zerkms 2012-01-30 03:34:43

+2

如果您有錯誤,請提及它。 – Starx 2012-01-30 03:38:12

回答

62

簡單多了:

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

在回答關於內存使用情況的意見:

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

更簡單但更耗費內存 – zerkms 2012-01-30 03:38:51

+1

不必將整個文本加載到內存中。 – xdazz 2012-01-30 03:43:06

+1

@zerkms現在怎麼樣? – 2014-03-15 12:31:50

16

的是代碼效率更高同時搜索更大的文件。

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

ps,「更高效」,他的意思是'可能更慢(除非file_get_contents使用太多內存以至於開始交換,在這種情況下,這可能會更快),但是應該使用更少的ram',並警告,該算法將不會尋找包含換行符的字符串的工作,除非唯一的換行符在字符串的末尾,請記住:) – hanshenrik 2017-12-01 23:11:01

+0

他確實說過「較大的文件」,如果文件變得非常大(比如帶有真正文件的文件許多密碼哈希最近發佈)可能很容易達到內存限制 – My1 2018-02-23 07:24:03

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

相關問題