function FileSystem::saveData

Same name and namespace in other branches
  1. 9 core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::saveData()
  2. 8.9.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::saveData()
  3. 11.x core/lib/Drupal/Core/File/FileSystem.php \Drupal\Core\File\FileSystem::saveData()

Saves a file to the specified destination without invoking file API.

This function is identical to writeData() except the file will not be saved to the {file_managed} table and none of the file_* hooks will be called.

Parameters

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

string $destination: A string containing the destination location. This must be a stream wrapper URI.

\Drupal\Core\File\FileExists|int $fileExists: Replace behavior when the destination file already exists.

Return value

string A string with the path of the resulting file, or FALSE on error.

Overrides FileSystemInterface::saveData

File

core/lib/Drupal/Core/File/FileSystem.php, line 478

Class

FileSystem
Provides helpers to operate on files and stream wrappers.

Namespace

Drupal\Core\File

Code

public function saveData($data, $destination, $fileExists = FileExists::Rename) {
  if (!$fileExists instanceof FileExists) {
    // @phpstan-ignore-next-line
    $fileExists = FileExists::fromLegacyInt($fileExists, __METHOD__);
  }
  // Write the data to a temporary file.
  $temp_name = $this->tempnam('temporary://', 'file');
  if (file_put_contents($temp_name, $data) === FALSE) {
    throw new FileWriteException("Temporary file '{$temp_name}' could not be created.");
  }
  // Move the file to its final destination.
  return $this->move($temp_name, $destination, $fileExists);
}

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