Q:

How to use shell exec grep to search multiple words in a file in php

Here is my code
$words=$_GET['word'];
$words=explode(' ',$words);
$words=implode('|',$words);
$search=shell_exec( 'grep -E '.$words.' 
/home/jitu/data.txt');
$search=explode('\n',$search);
foreach($search as $line){echo '<p>'.$line.'</p>';}

This code works best for single search word but is not working in multiple words

A:

When using the $words variable in shell_exec you need to enclose it within quotes.
The '|' (pipe symbol) passes the result of the command on the left to the command on the right.
Your shell is executing this:
$: grep -E one|two|three data.txt 
bash: two: command not found
bash: three: command not found  

When it should be executing this:
$: grep -E 'one|two|three' data.txt 
one
two

Code:
<?php
$words="one two three";
$words=explode(' ',$words);
$words=implode('|',$words);
$search=shell_exec( "grep -E '{$words}' data.txt");
$search=explode('\n',$search);
foreach($search as $line){echo '<p>'.$line.'</p>';};

On a side note, as your passing user supplied input to shell_exec without sanitizing it first you are leaving yourself vulnerable to code execution.

