Skip to content

Instantly share code, notes, and snippets.

@BhargavBhandari90
Last active September 17, 2025 15:28
Show Gist options
  • Save BhargavBhandari90/e54f3b5ca42835327e4931f9f914db05 to your computer and use it in GitHub Desktop.
Save BhargavBhandari90/e54f3b5ca42835327e4931f9f914db05 to your computer and use it in GitHub Desktop.
Scan images in bacth and store to json file.
<?php
// Scan images in batch
function fp_image_scan_batch($batch_size = 500, $reset = false)
{
$upload_dir = wp_get_upload_dir();
$batch = [];
$log_file = trailingslashit(WP_CONTENT_DIR) . 'fp-image-scan.log';
// Reset log file on first batch
if($reset || !file_exists($log_file)) {
file_put_contents($log_file, "");
}
// Get already logged images
$logged = file($log_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if(!is_array($logged)) {
$logged = [];
}
$lookup = array_flip($logged); // Make a lookup for O(1) checks
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($upload_dir['basedir'], FilesystemIterator::SKIP_DOTS)
);
foreach($iterator as $file){
if($file->isFile() && in_array(strtolower($file->getExtension()), ['jpg', 'jpeg', 'png'], true)){
$link = str_replace($upload_dir['basedir'], $upload_dir['baseurl'], $file->getPathname());
// Skip already logged images
if (isset($lookup[$link])) {
continue;
}
$batch[] = $link;
if (count($batch) >= $batch_size) {
break;
}
}
}
if(!empty($batch)){
$log_content = implode(PHP_EOL, $batch) . PHP_EOL;
error_log($log_content, 3, $log_file);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment