delete files that are not in mysql database

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Cammet
Forum Newbie
Posts: 22
Joined: Thu Sep 23, 2004 8:00 am

delete files that are not in mysql database

Post 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?
User avatar
Sema
Forum Commoner
Posts: 34
Joined: Fri Sep 03, 2004 12:43 pm
Location: Aalborg, Denmark

Post 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
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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
   }
}
Post Reply