-2

i try to execute a grep command inside a php shell_exec. And it works fine besides it fails when i have a underscore in the search word. I can not seem to figure out why this fails because of a underscore since, a grep command with a underscore in search word works in shell code below:

$output = shell_exec("grep -l -r '$search_word'"); 

The content in search_word variable is dynamic from database but the word that gives me trouble is base_64

PatrickSH
  • 27
  • 4
  • $search_word is a variable, what is the content? – Nuno Costa Oct 22 '15 at 09:12
  • The content is dynamic from database but the word that have underscore in is base_64 – PatrickSH Oct 22 '15 at 09:13
  • @Amarnasan i dont belive that is a possible solution for me since the variable content is dynamic and dont contain a underscore every single time – PatrickSH Oct 22 '15 at 09:17
  • @Amarnasan Except that that duplicate does not apply here! (As far as one is able to tell from the sparse information here.) – deceze Oct 22 '15 at 09:17
  • 1
    @PatrickSH 1) Show us an example of `echo "grep -l -r '$search_word'"` which doesn't work. 2) What exactly does "doesn't work" mean?! What's happening, what do you expect to happen? – deceze Oct 22 '15 at 09:19
  • @deceze sorry if i haven't been clear enough i have a database with search words. For example: base_64, eval, – PatrickSH Oct 22 '15 at 09:24
  • That vaguely answers the first part of my question, it does not answer the second part. – deceze Oct 22 '15 at 09:25
  • @deceze Sorry. Part 2 then. If a grep with one of these words returns true i want the filename to go into my database and again this hole process works like a charm except with words that contains an underscore. – PatrickSH Oct 22 '15 at 09:27
  • @deceze i see now that not only the underscore is my problem but numbers too? – PatrickSH Oct 22 '15 at 09:41

2 Answers2

0

Before PHP spawns a subprocess your command will be $search_word evaluated:

grep -l -r '....'
# So in $search_word is set to `john doe` it will become:
grep -l -r 'john doe'

How PHP behaves I'm not sure, it might be stalling waiting for the process to finish, it might have been closing stdin already.

Your above command will expect input from stdin because no file name is specified, breakdown:

grep [option]... [pattern] [file]...
-l will only print file name of the matched file
-r recursive search.

TLDR: You properly want to specify a file / directory to search in:

$output = shell_exec("grep -l -r '$search_word' ."); 
// Or maybe
$output = shell_exec("grep -l -r '${search}_word' ."); # will use $search variable as an input from PHP while _word is a string now.
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
0

Try like this: $output = shell_exec("grep -l -r '$search_word' ./*");

Anoxy
  • 873
  • 7
  • 17