Page 1 of 1

delete files that are not in mysql database

Posted: Wed Sep 29, 2004 3:28 am
by Cammet
I am trying to compare a directory that contains picture files with a mysql column that contains the url to these picture files and if there are any picture files in that directory that are not in the database i would like them unlinked. So far i can print out the results of both the column and the folder but im not sure where to go next.

Code: Select all

<?php
if ($handle = opendir('/home/path/files/')) {
   while (false !== ($file = readdir($handle))) { 
       if ($file != "." && $file != ".." && $file!="trans.gif") { 
           echo "http://www.url.com/files/$file<br>\n"; 
       } 
   }
   closedir($handle); 
}
echo("<br><br> From Mysql<br><br>");

@mysql_connect(localhost, username, pass) or die("ERROR--CAN'T CONNECT TO SERVER"); 
   @mysql_select_db(database) or die("ERROR--CAN'T CONNECT TO DB");

$sql = "SELECT * FROM messages";

$result = mysql_query($sql) or die(mysql_error());

while($row = mysql_fetch_array($result)){

$variable1=$row["image"];
if ($variable1 !="/files/trans.gif" && $variable1!="files/trans.gif")
{
echo("$variable1<br>");
}
}

?>
the only picture file i dont want to delete is trans.gif
Anyone have an idea?

Posted: Wed Sep 29, 2004 7:33 am
by Sema
When you find the files in the dir, then you could search your db after the same file, and if it isn't in the db then delete the file.... or you could put your results in a array and then compare the results

Posted: Wed Sep 29, 2004 7:38 am
by timvw
assuming you have an array $remote and $local

Code: Select all

// get the remote files we don't have locally
foreach($remote as $file)
{
  if (!in_array($file, $local))
  {
      // do thingies
   }
}