file_save_data

Versions
4.6 – 6
file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
7
file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)

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

See also

file_unmanaged_save_data()

Parameters

$data A string containing the contents of the file.

$destination A string containing the destination URI. 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. If a managed file with the destination name exists then its database entry will be updated. If no database entry is found then a new one will be created.
  • 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

▾ 1 function calls file_save_data()

system_retrieve_file in modules/system/system.module
Attempts to get a file using drupal_http_request and to store it locally.

Code

includes/file.inc, line 1438

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

  if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {
    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = basename($uri);
    $file->filemime = file_get_mimetype($file->uri);
    $file->uid      = $user->uid;
    $file->status  |= FILE_STATUS_PERMANENT;
    // If we are replacing an existing file re-use its database record.
    if ($replace == FILE_EXISTS_REPLACE) {
      $existing_files = file_load_multiple(array(), array('uri' => $uri));
      if (count($existing_files)) {
        $existing = reset($existing_files);
        $file->fid = $existing->fid;
        $file->filename = $existing->filename;
      }
    }
    // If we are renaming around an existing file (rather than a directory),
    // use its basename for the filename.
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
      $file->filename = basename($destination);
    }

    return file_save($file);
  }
  return FALSE;
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.