function file_save_data

Same name in other branches
  1. 7.x includes/file.inc \file_save_data()
  2. 8.9.x core/modules/file/file.module \file_save_data()

Saves a file to the specified destination and creates a database entry.

Parameters

string $data: A string containing the contents of the file.

string|null $destination: (optional) A string containing the destination URI. This must be a stream wrapper URI. If no value or NULL is provided, a randomized name will be generated and the file will be saved using Drupal's default files scheme, usually "public://".

int $replace: (optional) The replace behavior when the destination file already exists. Possible values include:

Return value

\Drupal\file\FileInterface|false A file entity, or FALSE on error.

Throws

\Drupal\Core\Entity\EntityStorageException Thrown when there is an error updating the file storage.

Deprecated

in drupal:9.3.0 and is removed from drupal:10.0.0. Use \Drupal\file\FileRepositoryInterface::writeData() instead.

See also

https://www.drupal.org/node/3223520

\Drupal\Core\File\FileSystemInterface::saveData()

1 call to file_save_data()
LegacyFileTest::testSaveData in core/modules/file/tests/src/Kernel/LegacyFileTest.php
Tests file_save_data deprecation and that it works without a destination.

File

core/modules/file/file.module, line 519

Code

function file_save_data($data, $destination = NULL, $replace = FileSystemInterface::EXISTS_RENAME) {
    @trigger_error(__FUNCTION__ . ' is deprecated in drupal:9.3.0 and will be removed in drupal:10.0.0. Use \\Drupal\\file\\FileRepositoryInterface::writeData() instead. See https://www.drupal.org/node/3223520', E_USER_DEPRECATED);
    if (empty($destination)) {
        $destination = \Drupal::config('system.file')->get('default_scheme') . '://';
    }
    
    /** @var \Drupal\file\FileRepositoryInterface $fileRepository */
    $fileRepository = \Drupal::service('file.repository');
    try {
        return $fileRepository->writeData($data, $destination, $replace);
    } catch (InvalidStreamWrapperException $e) {
        \Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', [
            '%destination' => $destination,
        ]);
        \Drupal::messenger()->addError(t('The data could not be saved because the destination is invalid. More information is available in the system log.'));
        return FALSE;
    } catch (FileException $e) {
        return FALSE;
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.