Definition

file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
drupal/includes/file.inc, line 1132

Description

Save a string to the specified destination and create a database file entry.

@see file_unmanaged_save_data()

Parameters

$data A string containing the contents of the file.

$destination A string containing the destination location. If no value is provided then a randomly name will be generated and the file saved in Drupal's files directory.

$replace Replace behavior when the destination file already exists:

  • FILE_EXISTS_REPLACE - Replace the existing file.
  • FILE_EXISTS_RENAME - Append _{incrementing number} until the filename is unique.
  • FILE_EXISTS_ERROR - Do nothing and return FALSE.

Return value

A file object, or FALSE on error.

Related topics

Namesort iconDescription
File interfaceCommon file handling functions.

Code

function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  global $user;

  if ($filepath = file_unmanaged_save_data($data, $destination, $replace)) {
    // Create a file object.
    $file = new stdClass();
    $file->filepath = $filepath;
    $file->filename = basename($file->filepath);
    $file->filemime = file_get_mimetype($file->filepath);
    $file->uid      = $user->uid;
    $file->status  |= FILE_STATUS_PERMANENT;
    return file_save($file);
  }
  return FALSE;
}