Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Created July 20, 2014 04:30
Show Gist options
  • Save alastairparagas/c5a78ce54f64a9200aab to your computer and use it in GitHub Desktop.
Save alastairparagas/c5a78ce54f64a9200aab to your computer and use it in GitHub Desktop.
Looks for file locations stored in the database and if there are files in the filesystem that do not exist in the database, they are deleted. At the end of execution, an array of images that were found in the database but not in the filesystem are var_dumped.

DB-stored filepath - filesystem cleaner

What is it?

This is a sample script that shows how you can traverse a database stored with certain path locations. Images that are in a specific folder in the filesystem that are not stored in the database, are deleted. At the end of the script's execution, images that were in the database but not found in the filesystem are var_dumped on to the screen.

<?php
$connect = mysqli_connect("localhost", "root", "", "r8m3");
$query = mysqli_query($connect, "SELECT * FROM images");
$images = array();
while($result = mysqli_fetch_assoc($query)){
$images[] = $result["id"];
}
$handle = opendir("C:\\xampp\\htdocs\\R8M3\\public\\images");
while( ($file = readdir($handle)) !== FALSE ){
if( $file == '.' || $file == '..'){
continue;
}
$actualFile = "C:\\xampp\\htdocs\\R8M3\\public\\images\\" . $file;
$actualFileInfo = pathinfo($actualFile);
if(!in_array($actualFileInfo['filename'], $images)){
unlink($actualFile);
}
unset($images[array_search($actualFileInfo['filename'], $images)]);
}
// Remaining images
var_dump($images);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment