Delete files not in database





5
Date Submitted Tue. Sep. 4th, 2007 2:13 PM
Revision 1 of 1
Helper explode
Tags mysql | PHP
Comments 0 comments
I made this script to delete any unneeded files from the server that weren't being used by the database. Of course you can expand this a lot more, but I cut it down a little to put it up here.


<?php

/*
Just change $dir to whatever your directory is and change the SQL query to search for whatever file you need in the DB
*/


function deleteFiles(){
        $del_items = array();
        $files = array();
       
        $dir = '/user_images';
        $path = opendir($dir);
       
        while(false !== ($file = readdir($path))){
        if ($file != "." && $file != ".."){
            if(file_exists($dir.$file)) $files[] = $file
        }
    }   
        closedir($path);
       
        //Make DB connection here
       
        //see if files are in the DB or not
        foreach($files as $file){
                $sql = "SELECT userid FROM users WHERE main_image = \"$file\"";
                $result = mysql_query($sql);
                if(mysql_num_rows($result) == 0){
                        $del_items[] = $file;
                        unlink($dir.$file);
                }
        }

        //View the files you deleted
        echo "<pre>";
        print_r($del_items);
        echo "</pre>";
}

?>

 

Comments

There are currently no comments for this snippet.

Voting

Votes Down