← Назад к справке

Ядро

Пользователи и файлы

Рабочая справка по пользователям и файлам в Bitrix Framework: UserTable, выборка пользователей, Bitrix\Main\IO\File, чтение, запись и проверка файлов.

Для чтения пользователей в новом коде удобно использовать UserTable. Для работы с файлами — Bitrix\Main\IO\File, особенно если нужен D7-стиль вместо прямых file_get_contents() и file_put_contents().

Пользователи

UserTable — D7-класс для работы с таблицей пользователей.

UserTable

<?php

use Bitrix\Main\UserTable;

/**
 * Получает карту полей пользователя.
 */
function fetchUserMap(): array
{
    return UserTable::getMap();
}

$user_map = fetchUserMap();

print_r($user_map);

Получить пользователя

<?php

use Bitrix\Main\UserTable;

/**
 * Получает пользователя по ID.
 */
function fetchUserById(int $user_id): array
{
    if ($user_id <= 0) {
        return [];
    }

    $user = UserTable::getList([
        'select' => [
            'ID',
            'LOGIN',
            'NAME',
            'LAST_NAME',
            'EMAIL',
            'ACTIVE',
        ],
        'filter' => [
            '=ID' => $user_id,
        ],
        'limit' => 1,
    ])->fetch();

    return is_array($user) ? $user : [];
}

$user = fetchUserById($user_id);

print_r($user);

Получить список пользователей

<?php

use Bitrix\Main\UserTable;

/**
 * Получает активных внутренних пользователей.
 */
function fetchActiveInternalUsers(): array
{
    $users = [];

    $user_result = UserTable::getList([
        'select' => [
            'ID',
            'LOGIN',
            'NAME',
            'LAST_NAME',
            'EMAIL',
        ],
        'filter' => [
            '=ACTIVE' => 'Y',
            '=EXTERNAL_AUTH_ID' => '',
        ],
        'order' => [
            'ID' => 'ASC',
        ],
        'limit' => 100,
    ]);

    while ($user = $user_result->fetch()) {
        $users[] = $user;
    }

    return $users;
}

$users = fetchActiveInternalUsers();

print_r($users);

Файлы

Bitrix\Main\IO\File работает с файлами через объектный D7-интерфейс.

IO\File

<?php

use Bitrix\Main\Application;
use Bitrix\Main\IO\File;

/**
 * Создаёт объект файла по относительному пути.
 */
function createLocalFile(string $relative_path): File
{
    $file_path = Application::getDocumentRoot() . $relative_path;

    return new File($file_path);
}

$file = createLocalFile('/local/logs/example.log');

echo $file->getPath();

Прочитать и записать файл

<?php

use Bitrix\Main\Application;
use Bitrix\Main\IO\File;

/**
 * Записывает строку в файл.
 */
function writeFileContent(string $relative_path, string $content): void
{
    $file_path = Application::getDocumentRoot() . $relative_path;

    File::putFileContents($file_path, $content);
}

/**
 * Дописывает строку в файл.
 */
function appendFileContent(string $relative_path, string $content): void
{
    $file_path = Application::getDocumentRoot() . $relative_path;

    File::putFileContents($file_path, $content, File::APPEND);
}

/**
 * Читает содержимое файла.
 */
function readFileContent(string $relative_path): string
{
    $file_path = Application::getDocumentRoot() . $relative_path;

    if (!File::isFileExists($file_path)) {
        return '';
    }

    return (string) File::getFileContents($file_path);
}

writeFileContent('/local/logs/example.log', 'Первая строка' . PHP_EOL);
appendFileContent('/local/logs/example.log', 'Вторая строка' . PHP_EOL);

$content = readFileContent('/local/logs/example.log');

echo $content;

Проверить файл

<?php

use Bitrix\Main\Application;
use Bitrix\Main\IO\File;

/**
 * Получает информацию о файле.
 */
function fetchFileInfo(string $relative_path): array
{
    $file_path = Application::getDocumentRoot() . $relative_path;
    $file = new File($file_path);

    if (!$file->isExists()) {
        return [
            'is_exists' => false,
        ];
    }

    return [
        'is_exists' => true,
        'name' => $file->getName(),
        'extension' => $file->getExtension(),
        'size' => $file->getSize(),
        'is_readable' => $file->isReadable(),
        'is_writable' => $file->isWritable(),
    ];
}

$file_info = fetchFileInfo('/local/logs/example.log');

print_r($file_info);

Источники