2012-10-05 46 views
0

我想通过php执行一个shell命令并在浏览器中显示它。无论如何要这样做? 这里是我的PHP代码:[test.php的]通过php执行shell命令并将其显示在浏览器中?

<?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命令不工作?

回答

0

egrep命令不工作,因为您使用单引号作为字符串常量分隔符:'egreep -w' < ==>​​< ==>/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'); 
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"); 
+0

太棒了:)非常感谢! – sree127

+0

嘿,$ output = shell_exec('tail -f | egrep“$ number。* $ date”/var/www/myquery_test/log/push.log')不起作用。是因为'|'吗?符号??任何选择? – sree127

+0

@ user1640534这不是因为管道,这是因为单引号。 PHP不解析单引号的内容。我将为我的答案添加各种替代方案 –

相关问题