Executing system command in PHP differs when using

2019-08-23 06:45发布

问题:

I have to execute a Linux more command in PHP from a particular offset, format the result and display the result in the browser.

My code for the above is:

<html>
<head>
    <META HTTP-EQUIV=REFRESH CONTENT=10>
    <META HTTP-EQUIV=PRAGMA CONTENT=NO-CACHE>
    <title>Runtime Access log</title>
</head>
<body>
    <?php
    $moreCommand = "more +3693 /var/log/apache2/access_log | grep -v -e '.jpg' -e '.jpeg' -e '.css' -e '.js' -e '.bmp' -e '.ico'| wc -l";
     exec($moreCommand, $accessDisplay);
     echo "<br/>No of lines are : $accessDisplay[0] <br/>";
    ?>
</body>
</html>

The output at the browser is: No of lines are : 3428 (This is wrong)

While executing the same command using command line gives a different output. My code snippet for the same is:

<?php
    $moreCommand = "more +3693 /var/log/apache2/access_log | grep -v -e '.jpg' -e '.jpeg' -e '.css' -e '.js' -e '.bmp' -e '.ico'| wc -l";

    exec($moreCommand, $accessDisplay);
    echo "No of lines are : $accessDisplay[0] \n";
?>

The output at the command line is: No of lines are : 279 (This is correct)

While executing the same command directly in command line, gives me output as 279.

I am unable to understand why the output of the same command is wrong in the browser. Its actually giving the word count of lines, ignoring the offset parameter.

回答1:

I would recommend that you drop the shell pipeline and parse the logfile in PHP directly. Much more control. Much less hassle and definitely more robust.



回答2:

What would the difference be in:

$moreCommand = "more -f -99999 +3693 /var/log/apache2/access_log | grep -v -e '.jpg' -e '.jpeg' -e '.css' -e '.js' -e '.bmp' -e '.ico' -c"

(-f & -num to more, -c to grep instead of | wc -l)

In debugging it could also be usefull to examine the exact output without count of the 2 (perhaps using head or tail), as there might be shell differences between the cli & webserver users.


OK, that was wrong, can reproduce more not getting the '+', alternative:

$moreCommand = "tail --lines=`wc -l /var/log/apache2/access_log  | awk '{print $1 - 3693}'  | grep -v -e '.jpg' -e '.jpeg' -e '.css' -e '.js' -e '.bmp' -e '.ico' `


标签: php linux