Clearing the upload folder of unused files
Rus
Eng
Очистка папки upload от неиспользуемых файлов

All English-language materials have been translated fully automatically using the Google service

On large or old projects, cleaning up the uploads folder often becomes an unnecessary headache. I suggest using the console solution from Alexander Kuntashov and George Melikov

Download the clear_upload.php file and place it in any convenient folder

Listing of the clear_upload.php file:

#!/usr/bin/env php
<?php set_time_limit(0); 

if (count($argv) < 2) {
    echo <<< USAGE

Usage: php clear_upload.php [--delete-files] [--move-files = / path / to] / path / to / document / root

Script for clearing the upload / iblock directory from unused files (remaining after deleting an infoblock element).
Checks each file in the upload / iblock directory to see if it is in the b_file table and, if it is not there, displays the complete
the path to it on the screen.

If the --move-file = / path option is specified, then it moves the file to the specified directory while maintaining the hierarchy.

If the --delete-files option is specified, then deletes the file. In delete mode (with the --delete-files option),
if the directory in which the file to be deleted is empty, it deletes it too.

Examples of using:

Get a list of all unused files from upload / iblock directory:
    
    php clear_upload.php /var/www/example.com
    
Move all unused files from upload / iblock directory to / backup folder:
    
    php clear_upload.php --move-files=/backup /var/www/example.com

Remove all unused files from upload / iblock directory:
    
    php clear_upload.php --delete-files /var/www/example.com

USAGE;
    exit(0);
}

////////////////////////////////////////////////////////////////////////////////////////////

$command='';
$commandvalue='';

// Проверяем аргументы
if ( substr( $argv[1], 0, 2 ) === '--' ) {
	$argv[1] = substr( $argv[1], 2 );
	if (strpos($argv[1],'=')) {
		list($command,$commandvalue) = explode("=",$argv[1],2);
	} else {
		$command = $argv[1];
	}
}

$_SERVER['DOCUMENT_ROOT'] = $DOCUMENT_ROOT = count($argv) > 2 ? $argv[2] : $argv[1];

#define("LANG", "ru"); 
define("NO_KEEP_STATISTIC", true); 
define("NOT_CHECK_PERMISSIONS", true); 
 
$prolog = $_SERVER['DOCUMENT_ROOT'] . "/bitrix/modules/main/include/prolog_before.php";
if (file_exists($prolog)) include($prolog); else die("The specified directory is not the root directory of the site on 1C-Bitrix" . PHP_EOL);

// Create a file name cache based on the b_file table.
$arFilesCache = array();
$result = $DB->Query('SELECT FILE_NAME, SUBDIR FROM b_file WHERE MODULE_ID = "iblock"');
while ($row = $result->Fetch()) {
    $arFilesCache[ $row['FILE_NAME'] ] = $row['SUBDIR'];
}

$rootDirPath = $_SERVER['DOCUMENT_ROOT'] . "/upload/iblock";
$hRootDir = opendir($rootDirPath);
$count = 0;
while (false !== ($subDirName = readdir($hRootDir))) {
    if ($subDirName == '.' || $subDirName == '..') 
        continue;
    $subDirPath = "$rootDirPath/$subDirName";
    $hSubDir = opendir($subDirPath);    
    while (false !== ($fileName = readdir($hSubDir))) {
        if ($fileName == '.' || $fileName == '..') 
            continue;
        if (array_key_exists($fileName, $arFilesCache)) {
            continue;
        }
        $fullPath = "$subDirPath/$fileName";
        if ($command=='delete-files') {
            if (unlink($fullPath)) {
                echo "Removed: " . $fullPath . PHP_EOL;
            }
        } elseif ($command=='move-files' && !empty($commandvalue)) {
			mkdir("$commandvalue/$subDirName",0775, true);
			if (rename($fullPath, "$commandvalue/$subDirName/$fileName")) {
				echo "Move: " . $fullPath . PHP_EOL;
			}
		}
        else {
            echo $fullPath . PHP_EOL;
        }
    }
    closedir($hSubDir);
    if (!empty($command)) {
		//delete empty directory
		@rmdir($subDirPath);
    }
}
closedir($hRootDir);

require($_SERVER["DOCUMENT_ROOT"]."/bitrix/modules/main/include/epilog_after.php");

Turn on short_open_tag = On in php.ini

Usage examples:

//Get a list of all unused files from upload / iblock directory:
php clear_upload.php /var/www/example.com

//Move all unused files from upload / iblock directory to / backup folder:
php clear_upload.php --move-files=/backup /var/www/example.com

//Remove all unused files from upload / iblock directory:
php clear_upload.php --delete-files /var/www/example.com

 

Solution used:

Comments

There are no comments yet, you can be the first to leave it

Leave a comment

The site uses a comment pre-moderation system, so your message will be published only after approval by the moderator

You are replying to a user's comment

Send

FEEDBACK

Email me

Are you developing a new service, making improvements to the existing one and want to be better than your competitors? You have come to the right place. I offer you a comprehensive studio-level website development. From me you can order design, layout, programming, development of non-traditional functionality, implementation of communication between CMS, CRM and Data Analitics, as well as everything else related to sites, except for promotion.

Contact, I will always advise on all questions and help you find the most effective solution for your business. I am engaged in the creation of sites in Novosibirsk and in other regions of Russia, I also work with the CIS countries. You will be satisfied with our cooperation

An error occurred while sending, please try again after a while
Message sent successfully

Phones

+7(993) 007-18-96

Email

info@tichiy.ru

Address

Россия, г. Москва

By submitting the form, you automatically confirm that you have read and accept the Privacy Policy site

Contact with me
Send message
By submitting the form, you automatically confirm that you have read and accept Privacy policy of site
Sending successful!
Thank you for contacting :) I will contact you as soon as possible
Sending failed
An error occurred while sending the request. Please wait and try again after a while or call my phone number