【问题标题】:Execute a shell command through php and display it in browser?通过php执行shell命令并在浏览器中显示?
【发布时间】:2012-09-26 11:31:44
【问题描述】:

我想通过php执行一个shell命令并在浏览器中显示。反正有这样做吗? 这是我的 php 代码:[test.php]

<?php
$number=$_GET["num"];
$date=$_GET["date"];
$output = shell_exec('egrep -w  '2012-09-01|974' /home/myquery_test/log/push.log');
echo "<pre>$output</pre>";
?>

当我从浏览器运行这个(test.php) 文件时,什么也没有出现。但是当我改变

$output = shell_exec('ls')

它工作正常!!为什么 egrep/grep 命令不起作用?

【问题讨论】:

    标签: php linux shell grep


    【解决方案1】:

    egrep 命令不起作用,因为您使用单引号作为字符串常量分隔符:'egreep -w' 2012-09-01|974' /home/myquery_test/log/push.log' 只是在字符串中使用双引号,或作为字符串分隔符 OR 转义引号。

    shell_exec('egrep -w  \'2012-09-01|974\' /home/myquery_test/log/push.log');
    shell_exec('egrep -w  "2012-09-01|974" /home/myquery_test/log/push.log');
    shell_exec("egrep -w  '2012-09-01|974' /home/myquery_test/log/push.log");
    

    并且,为了避免在测试时没有收到可能导致此问题暴露的警告和错误,请将您的 ini 设置为 E_STRICT|E_ALL,并修复警告,而不是忽略它们。 [戏谑:在你完成之后,你可能要考虑accepting some answers]我看到你在我写这篇文章的时候已经接受了很多:)

    在命令中使用变量:

    $output = shell_exec("tail -f | egrep '$number.*$date' /var/www/myquery_test/log/push.log");
    $output = shell_exec('tail -f | egrep "'.$number.'.*'.$date.'" /var/www/myquery_test/log/push.log');
    $output = shell_exec("tail -f | egrep \"$number.*$date\" /var/www/myquery_test/log/push.log");
    

    【讨论】:

    • 太棒了 :) 非常感谢!!
    • 嘿,$output = shell_exec('tail -f | egrep "$number.*$date" /var/www/myquery_test/log/push.log') 不起作用。是不是因为'|'象征??有什么选择吗?
    • @user1640534 这不是因为管道,而是因为单引号。 PHP 不解析单引号的内容。我会为我的答案添加各种替代方案
    • @user1640534:我刚刚注意到您将$_GET 变量传递给您的shell,而没有清理&amp;#! 等字符的输入。这是一个巨大的安全漏洞,可以是plugged quite easily
    猜你喜欢
    • 2015-07-12
    • 2010-10-07
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2013-08-25
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多