PHP 文件搜索内存限制


PHP file search memory limit

我使用此代码在服务器上的php文件中搜索特定代码。可能是,它通常需要一些时间并给出致命错误(超出内存限制)。有没有办法让这段代码更"优雅"?

<?php
ini_set('display_errors', 1); 
ini_set('memory_limit', '128M');
error_reporting(E_ALL);
define("SLASH", stristr($_SERVER['SERVER_SOFTWARE'], "win") ? "''" : "/");
if (isset($_POST['path']))
    $path    = ($_POST['path']) ? $_POST['path'] : dirname(__FILE__) ;
else
    $path = dirname(__FILE__) ;
if (isset($_POST['q']))
    $q        = $_POST['q'];

function php_grep($q, $path){
    $temp_array = array();
    $ret = '';
    $fp = opendir($path);
    while($f = readdir($fp)){
        if( preg_match("#^'.+$#", $f) ) continue; // ignore symbolic links
        $file_full_path = $path.SLASH.$f;
        if(is_dir($file_full_path)) {
            $ret .= php_grep($q, $file_full_path);
        } else if( stristr(file_get_contents($file_full_path), $q) ) {
            $ret .= "$file_full_path'n";
        }
    }
    foreach($temp_array as $t)
        $ret .= php_grep1($q, $t);
    return $ret;
}
if (isset($_POST['q'])){
    $results = php_grep($q, $path);
}

?>
<form method=post>
    <input name=path size=100 value="<?php echo $path ?>" /> Path
    <input name=q size=100 value="<?php if (isset ($q)) echo $q; else echo 'mysql_connect';?>"  /> Query
    <input type=submit>
</form>
<?php if (isset($results)) echo $results."<br/>"; ?>

SSH被禁用,所以我不能使用它。叹息 grep 本来是一个更简单的解决方案。

谢谢大家。

而不是"file_get_contents"尝试使用

$fp = fopen( $file_full_path, 'r' );
$content = fread( $fp, filesize( $file_full_path ) );
fclose( $fp );
if( stristr( $content, $q ) )
{
    $ret .= $file_full_path . "'n"
}
unset( $content );

我看不出你有什么理由应该耗尽内存,一定是泄漏或其他什么。 如果失败,请使用"memory_get_peak_usage"功能来跟踪导致内存增加的部分。

它可能是$ret变量的串联,但您必须执行存储桶加载才能出现这种情况。您可以尝试改用数组,然后在搜索结束时将其内爆为字符串。

如果不知道您正在搜索的文件的细节,我就无法提出任何其他建议。