Hi,
I have a text file that contains names of files in a directory on my webspace. I would like to do is compare the files to the filenames in the textfile and delete the ones that dont exist.
The problem comes in comparing the textfile with the names of the files in the directory so as to unlink the ones that do not exist.
Any suggestions?
A logic/Syntax Question
Moderator: General Moderators
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
loop through your text file and store the filenames into an array
then loop through your directory and store those filenames into an array
use array_diff() to find the difference
then do a foreach on the resulting array and unlink
then loop through your directory and store those filenames into an array
use array_diff() to find the difference
then do a foreach on the resulting array and unlink
Set Search Time - A google chrome extension. When you search only results from the past year (or set time period) are displayed. Helps tremendously when using new technologies to avoid outdated results.
- shiznatix
- DevNet Master
- Posts: 2745
- Joined: Tue Dec 28, 2004 5:57 pm
- Location: Tallinn, Estonia
- Contact:
ok heres a example:
the textfile
here is the directory listing on your server
and thus you want to delete 'badfileahhh.php' and 'horribleness.html' right? here is a quick example
of course you are going to want to test everything first before you start deleting files
edit: and once again I am too slow, by just seconds this time. maybe I am speeding up?
the textfile
Code: Select all
file1.html
zoorg.html
beebop.htm
devnet.phpCode: Select all
file1.html
zoorg.html
badfileahhh.php
beebop.htm
devnet.php
horribleness.htmlCode: Select all
$txt = file_get_contents('textFile.txt');
$txtarr = explode("\n", $txt);
$dir = opendir('directory');
while (false !== ($file = readdir($dir)))
$dirarr[] = $file;
$all = array_diff($dirarr, $txtarr);
if (is_array($all))
{
foreach ($all as $key => $val)
unlink('directory/'.$val);
}edit: and once again I am too slow, by just seconds this time. maybe I am speeding up?