How to Delete Images on a Folder that Not Present on Mysql Data?

I have sub domain about cook recipes. This work automatically grab from other resources. It grabs text and images, store them on a writeable folder.

the problem is, when i migrate to another server, this image folder contains many files,  about 37.007 image files inside!

I realize that not all images name are stored in db, because it updated. So former image will be unused.
take a look.

Duplicate file with different name

Number 1, has two files identic, but different name. also 2 to 7.

so i need to delet that not exist on my db.

Compare this two folder

image above, show different count of files on that folder. Right side is original folder, and the left one is folder that run under php script to delete unused files on images folder. From 37007 to 36942, and still counting.

and below is the result. echoing deleted files.

Echoing deleted files

So, the script needed is.. a working script i found on SO

On my case script would be:

//set time limit, because it will take long process 🙂
set_time_limit (12500);

//set DB config according data stored on mysql
$servername = “localhost”;
$username = “USER_OF_DB”;
$password = “”;
$dbname = “NAME_OF_DB”;
$mysqli = mysqli_connect($servername, $username, $password, $dbname) or die(“Connection failed: ” . mysqli_connect_error());

//set target folder
$directory = “images/”;

//find type of image –> jpg
$images = glob($directory . “*.jpg”);

//looping data
foreach($images as $image)
$sql = “SELECT your_column FROM your_table_name  WHERE your_column =?”;
$stmt = $mysqli->prepare($sql);
if($stmt) {
$stmt->bind_param(‘s’, $image);

//if not present on mysql, delet it using unlink function
if(!$result) {
if(unlink($image)) {
//if succeed, just echo it
echo “Image deleted $image <br>\n”;
} else {
echo “Unable to prepare SQL”;


Mission Completed 🙂