0

I would like to execute a shell command through php and display it in a browser. Is there anyway to do so? here is my php code : [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>";
?>

When I run this(test.php) file from browser nothing shows up. But when i change the

$output = shell_exec('ls')

its working fine!! Why isn't the egrep/grep command not working??

sree127
  • 421
  • 3
  • 9
  • 25

1 Answers1

0

The egrep command isn't working, because you're using single quotes as a string constant delimiter: 'egreep -w' <==> 2012-09-01|974' <==> /home/myquery_test/log/push.log' <==
Just use double quotes in the string, or as string delimiters OR escape the quotes.

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");

And, to avoid not getting the warnings and errors that would have brought this issue to light when testing, set your ini to E_STRICT|E_ALL, and fix the warnings, rather then ignoring them. [teasingly: after you're done with that, you might want to consider accepting some answers]I see you've accepted a lot while I was typing this post up :)

Using variables in your command:

$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");
Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Hey, $output = shell_exec('tail -f | egrep "$number.*$date" /var/www/myquery_test/log/push.log') is not working. Is it because of the '|' symbol?? any alternative? – sree127 Oct 05 '12 at 10:58
  • @user1640534 It's not because of the pipe, it's because of the single quotes. PHP doesn't parse the contents of single quotes. I'll add various alternatives to my answer – Elias Van Ootegem Oct 05 '12 at 11:45
  • @user1640534: I just noticed you're passing `$_GET` variables to your shell, without sanitizing the input for chars like `&` or `#!`. This is a _massive_ security hole that can be [plugged quite easily](http://www.php.net/manual/en/function.escapeshellcmd.php) – Elias Van Ootegem Oct 05 '12 at 12:27