Page 1 of 1
A logic/Syntax Question
Posted: Tue Mar 21, 2006 2:16 am
by sosha
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?
Posted: Tue Mar 21, 2006 2:18 am
by s.dot
loop through your text file
check if
file_exists() and unlink if it doesn't
Posted: Tue Mar 21, 2006 2:32 am
by sosha
I did think of this but Im wondering, wont the first loop delete all the files that are not the same to the first filename in the textfile?
Posted: Tue Mar 21, 2006 3:11 am
by shiznatix
do you want to delete the files from the server or do you want to remove them from the text file?
Posted: Tue Mar 21, 2006 3:22 am
by s.dot
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
Posted: Tue Mar 21, 2006 3:33 am
by sosha
Hi
Sorry for not being clear. I want to delete the files from the server using the textfile as the guide on which filesnames of files NOT to delete are saved
Posted: Tue Mar 21, 2006 3:45 am
by sosha
HEY!
It works..WOW!
Thanks a million, I owe u one!
Posted: Tue Mar 21, 2006 3:45 am
by shiznatix
ok heres a example:
the textfile
Code: Select all
file1.html
zoorg.html
beebop.htm
devnet.php
here is the directory listing on your server
Code: Select all
file1.html
zoorg.html
badfileahhh.php
beebop.htm
devnet.php
horribleness.html
and thus you want to delete 'badfileahhh.php' and 'horribleness.html' right? here is a quick example
Code: 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);
}
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?