Monthly Archives: December 2015

How to find and Delete Files on Linux Server

A client of mine wanted a web interface to find and delete files by name on the server. He wanted it to search the entire server, so it will search from the / root directory up. Recursive search is needed for this.

Linux Command Line Command to Find a File by Name Anywhere on the Server

To simply find a file from a Linux command prompt if you know the name, use:
find / -name testfilexxx1.txt

...where testfile.txt is the file you are searching for.

Linux command to both find and delete file by name anywhere on the server:

find / -name testfilexxx1.txt -exec rm -rf {} \;

Running the find and delete file by Name From a PHP Script

The next task was to run the above command to find and delete a file by name anywhere on a server from a PHP script. In comes the exec PHP command!

Now we can run any shell command from PHP using the  shell_exec function, but we also have to specifiy that we want to view output somtimes, especially for debugging purposes as the output might not be right for your users to see. To be able to collect output from a shell_exec command, you have to add 2>&1 to the command so now our completed PHP script would look like this to find and replace a file by it's name:

<?php
if(isset($_POST['dels'])){
$delfilename = $_POST['delfilename'];
$retval = shell_exec("find / -name ".$delfilename." -exec rm -rf {} \; 2>&1");
echo "<br />$retval<p>$delfilename has been deleted from this server everywhere it was found<p>";
echo "<hr>Done!<br />";
}
?>
<h1>Find and Delete Files on This Server</h1>
<p>Note! Using this app will permanently delete any filename you enter into the below form on the entire server, so be sure you do not have other files with the same name elsewhere that you do not want deleted!</p>
<form method="post" action="">
File Name: <input type="text" id='delfilename' name='delfilename' />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="submit" id="dels" name="dels" value="DELETE FILE!" />
</form>

 Password protecting powerful scripts!

Of course, you don't want anyone visiting this page on your server and deleteing your files, right? well I have a solution for that as well. First thing you want to do is simply add a meta tag to keep search engines from indexing the page in the first place with the following meta tag:

<meta name="robots" content="noindex">

Simply insert the above meta tag before the closing head tag before the body HTML tag in your webpage you don't want to be searched.

Next, you want to password protect your page also just incase someone does stumble upon it. Here is another tutorial I wrote that includes the link to a password protection script that you can add to your page with a small download and adding one line of code to your page! See it here:

http://jafty.com/blog/tag/password-protect-any-page/