PHP file search memory limit
I use this code to search specific code in php files on the servers. Prob is, it usually takes some time and gives out Fatal errors (memory limit exceeded). Is there ay way to make this code more 'elegant'?
<?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_f开发者_如何学运维ull_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 is disabled, so I can't use that. sigh grep would have been an easier solution.
Thanks guys.
Instead of 'file_get_contents' try using
$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 );
I don't see any reason you should be running out of memory, it must be a leak or something. If that fails, utilise the 'memory_get_peak_usage' function to track down what part is causing the increase in memory.
It could possibly be the concatenation of the $ret variable, but you'd have to be doing a bucket load for that to be the case. You could try using an array instead and then imploding it to a string at the end of the search.
Without knowing the specifics of the files you're searching I cannot really make any other recommendations.
精彩评论