PHP Grep is your friend

By Haktan Suren, PhD
Feb 17th, 2015
2 Comments
13008 Views

Working with shared hosting has been always pain! having almost everything limited. Most shared hosting does not provide SSH access for the customers (unless you can convince them you know what you are doing). I generally need “SSH” access for finding a piece of code (class, css etc.) I need in bunch of files (usually thousands) easier with one of the most favorite Linux’s command “grep”.

Here is a piece of code written in PHP that you can use if your host is not providing the SSH access.

You can simply create a file and save it in public_html directory.

$folder = "./wp-content/plugins/*"; //If you want to search in current directory only use ./*
$search = "wcj_get_option_filter";
$command = "grep -nri '$search' $folder";
$output = shell_exec($command);
echo "<pre>";
echo "$output";
echo "</pre>";

Of course, it is up to you to make it more advanced. One idea might be using PHP’s “$_GET” variables so you do not have to edit the code on the server every time you want to search something. A very basic example would be as follow.

$folder = $_GET['folder'] != '' ? $_GET['folder'] : './*';
$search = $_GET['search'];
$command = "grep -nri '$search' $folder";
$output = shell_exec($command);
echo "<pre>";
echo "$output";
echo "</pre>";

By using the snippet above, you can run different grep commands without editing the code.

http://www.domain.com/grep.php?search=foo
http://www.domain.com/grep.php?search=bar

Please share your ideas and implementation below.

About the Author

Haktan Suren, PhD
- Webguru, Programmer, Web developer, and Father :)

2 Responses to “PHP Grep is your friend”

  1. anton nb says:

    i have this error on my shared hosting

    “Warning: exec() has been disabled for security reasons in….”

    what does this mean?

    • Haktan Suren, PhD Haktan Suren says:

      Hi anton, Thanks for replying to my post. It means, your host does not allow calling exec in PHP. Unfortunately, most of the shared hosts prevent some PHP functions like exec.
      There are some alternatives to exec()
      Can you try one of those system(); passthru(); shell_exec(); and let us know.
      Thanks

Wrap your code in <code class="{language}"></code> tags to embed!

Leave a Reply

E-mail address is required for commenting. However, it won't be visible to other users.

Loading Facebook Comments ...
Loading Disqus Comments ...