【发布时间】:2014-09-21 01:08:05
【问题描述】:
下面是我试图完成以查看我们 PBX 上的日志的代码。它运行良好,对日志文件进行排序,显示所有数据等。问题是一旦完成,它会在内存中保留大量数据(数百 MB)。完成后我需要清除它,但不知道如何。如果它运行了几次,它会从服务器中吸走所有的 RAM,然后我们就会开始出错。提前致谢!
<!DOCTYPE html>
<html>
<title>Call Search</title>
<body>
<?php
function getBetween($var1, $var2, $pool)
{
$temp1 = strpos($pool, $var1) + strlen($var1);
$result = substr($pool, $temp1, strlen($pool));
$dd=strpos($result, $var2);
if($dd == 0){$dd = strlen($result);}
return substr($result, 0, $dd);
}
if(!isset($_POST['phonenum']) && !isset($_POST['WantedCallID']))
{
echo '<form action="test.php" method="post">';
echo '<h4>Please enter the number you wish to search for...</h4><input type="text" name="phonenum">';
echo '<input type="submit" value="Go">';
echo '</form>';
}
else if(isset($_POST['WantedCallID']))
{
$counter = 0;
$logfile="calllog";
while (file_exists("/var/log/".$logfile))
{
if($counter==0){$logfile="calllog";}
else{$logfile="callog.".$counter;}
$path = "/var/log/".$logfile;
$logtoarray = file($path);
foreach ($logtoarray as $linenumber => $line)
{
if(strpos($line, "[".$_POST['WantedCallID']."]") !== false){echo $line." <br>";}
}
$counter++;
}
}
else
{
$counter = 0;
$logfile="calllog";
$arrayCounter = 0;
while (file_exists("/var/log/".$logfile))
{
if($counter == 0){$logfile = "calllog";}
else{$logfile="calllog.".$counter;}
$path = "/var/log/".$logfile;
if(file_exists($path))
{
$logtoarray = file($path);
$oldCallId = "";
$currentCallId = "";
foreach ($logtoarray as $linenumber => $line)
{
if(strpos($line, $_POST['phonenum']) !== false && strpos($line, "VERBOSE[") !== false)
{
$currentCallId = getBetween("VERBOSE[", "]", $line);
if($currentCallId !== $oldCallId)
{
$callIdArray[$arrayCounter] = "Date: ".substr($line, 0, 22)." Call ID:".$currentCallId."\n";
echo "Date: ".substr($line, 0, 22)." Call ID:".$currentCallId."<br>";
$oldCallId = $currentCallId;
}
}
$arrayCounter++;
}
}
else{break;}
$counter++;
}
echo '<form action="test.php" method="post">';
echo '<h4>Please enter the call ID you wish to search for...</h4><input type="text" name="WantedCallID">';
echo '<input type="submit" value="Go">';
echo '</form>';
}
$variables = array_keys(get_defined_vars());
foreach($variables as $variable) {
unset(${"$variable"});
}
unset($callIdArray);
?>
</body>
</html>
【问题讨论】:
-
Alister 在他的回答中所说的是正确的,但是还有另一个因素:您在我认为是一个相当大的日志文件上使用
file()。这是您的内存膨胀开始的地方,您可以通过使用fopen()/fgets()并以可管理的块迭代文件而不是将整个文件加载到内存中来显着减少内存占用一次。 -
是的,这些文件通常非常大而且非常冗长。我们将致力于切换我们调用文件的方式。现在我们已经将“MaxRequestsPerChild”设置从 4000 调整到 1000,但这感觉就像我们只是在绕开这个问题,而不是正面处理它。它也没有清除它。