TooCooL TooCooL - 2 months ago 11
PHP Question

search and delete unused images in articles with php

I have been working on some project and through time it got messed up with images which I tested it, so now I want to make a script which is going to search in articles img tags and find the img name (artiles are stored in mysql with attribute 'text') after scanning the folder where images are stored if they are not in any article included then to delete those images (unused images). Has anyone done this before so I could see an example or any good approach about this case?

Answer

Here's what you'll need to do what you want:

  1. Loop through your directory of files (if they are on the filesystem):

    if ($handle = opendir('/path/to/files')) {
    echo "Directory handle: $handle\n";
    echo "Entries:\n";
    
    /* This is the correct way to loop over the directory. */
    while (false !== ($entry = readdir($handle))) {
        echo "$entry\n";
    }
    
    /* This is the WRONG way to loop over the directory. */
    while ($entry = readdir($handle)) {
        echo "$entry\n";
    }
    
    closedir($handle);
    }
    

    Ref. http://php.net/readdir

  2. Loop through your files (if they are on the database):

    Ref. http://www.php.net/manual/en/mysqli.query.php

  3. Compare file names (obvious once you are looping through your resource).

  4. Delete unused images like so http://www.php.net/unlink