Created
March 2, 2024 14:22
-
-
Save samilkorkmaz/8b2d52c5bee4b6d82b00ba574303a2e0 to your computer and use it in GitHub Desktop.
Delete files that are not referenced from database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Delete image files in image/product/ folder that do not exist in database table products_photos, column photo | |
$directoryPath = 'c:/xampp_8_2_12/htdocs/image/product/'; | |
$removePath = 'c:/xampp_8_2_12/htdocs'; | |
$filesAndFolders = glob($directoryPath . '*'); // Note that some files don't have a file extension | |
$filesNotExistingInDatabase = array(); | |
$counter = 0; | |
// Part of the path to remove | |
foreach ($filesAndFolders as $i => $absolutePath) { | |
if (is_file($absolutePath)) { // exclude directories | |
$relativePath = str_replace($removePath, '', $absolutePath); | |
//$imageFileName = '/image/product/img-20220505-wa0010-jpg.jpg'; | |
$query = "SELECT * FROM products_photos WHERE photo='" . $relativePath . "'"; | |
$result = $db->query($query)->rows; | |
if (sizeof($result) < 1) { | |
$counter++; | |
echo $counter . ". " . $relativePath . " does not exist in products_photos table<br>"; | |
$filesNotExistingInDatabase[] = $relativePath; | |
if (unlink($absolutePath)) { | |
echo "The file was successfully deleted.<br>"; | |
} else { | |
echo "There was an error deleting the file.<br>"; | |
} | |
} | |
} | |
} | |
echo "sizeof(filesNotExistingInDatabase): " . sizeof($filesNotExistingInDatabase); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment