Searching server files using GREP

During debugging the majority of my time is spent in searching for specific text. Searching on the local machine is a breeze via a IDE, but if I’ve an application hosted on a remote server then it can get difficult and slow, unless of course you have access to SSH when you can use good-old Grep. But many times the server does not have SSH access at which time I have to rely on using Linux commands though PHP.

So for example the following will allow me to recursively search all the files in a directory for the string ” mail”. I just upload the file to the server directory from where I need to make the search. Here I’m using the PHP backtick operator that allows me to escape to the shell, execute the specified command, and return the result in the variable $output.

<?php
$output = `grep -r " mail" .`;
echo $output;
?>

The equivalent of the above using the shell_exec function is shown below.

<?php
$output = shell_exec('grep -r " mail" .');
echo $output;
?>

Note that the backtick operator and shell_exec are disabled if php is running in safe_mode so you will need to temporarily enable it to run the above code.

The above code searches for the specified string in all the files, but if you need to limit the search for a specific file type than you have to use find in combination with grep. So, the following will search for the string ‘ mail’ only in files with the .php extension.

<?php
$output = `find . -iname '*php' | xargs grep ' mail' `;
echo $output;
?>

By default grep lists the matched filename and also the matched line, but if you need to only list the filenames that contain the search term, you can use the ‘-l’ option with grep.

$output = `find . -iname '*php' | xargs grep ' mail' -l `;


2 thoughts on “Searching server files using GREP

Comments are closed.