Clearing the upload folder of unused files
Rus
Eng
Очистка папки upload от неиспользуемых файлов
I solve complex technical challenges for Bitrix and 1C—ranging from auditing existing code to website development and configuring complex integrations—with a guarantee of results.
Recommended

Website hosting

If you are choosing hosting for your project, I recommend Timeweb. Modern infrastructure, a wide range of plans from starter options to high-load VPS, and responsive tech support that actually helps instead of sending template replies. I host some of my own projects there and recommend it to my clients.

Go to site Affiliate link. The price remains the same for you.

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:

Aleksandr Tichiy
Author

Aleksandr Tichiy

Fullstack developer · 1C-Bitrix

I build and modernize online stores and corporate portals on 1C-Bitrix. Integrations with 1C, high-load performance, 152-FZ compliance. Writing about architecture and e-commerce.


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

Please message me to discuss the task. I work remotely and officially (as a self-employed professional); my hourly rate is 1,800 RUB, and I can dedicate 3–4 hours a day to the project. I respond quickly, and the consultation is free.

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