8.5.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8.0.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8.1.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8.2.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8.3.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8.4.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8.6.x file.module file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
4.6.x file.inc file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
4.7.x file.inc file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
5.x file.inc file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
6.x file.inc file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
7.x file.inc file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)

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


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

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

$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.

See also


Related topics

9 calls to file_save_data()
CronRunTestCase::testTempFileCleanup in modules/system/system.test
Ensure that temporary files are removed.
FileFieldTestCase::createTemporaryFile in modules/file/tests/file.test
Creates a temporary file, for a specific user.
FileSaveDataTest::testExistingError in modules/simpletest/tests/file.test
Test that file_save_data() fails overwriting an existing file.
FileSaveDataTest::testExistingRename in modules/simpletest/tests/file.test
Test file_save_data() when renaming around an existing file.
FileSaveDataTest::testExistingReplace in modules/simpletest/tests/file.test
Test file_save_data() when replacing an existing file.

... See full list


includes/file.inc, line 1892
API for handling file uploads and server file management.


function file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME) {
  global $user;
  if (empty($destination)) {
    $destination = file_default_scheme() . '://';
  if (!file_valid_uri($destination)) {
    watchdog('file', '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.', array(
      '%destination' => $destination,
    drupal_set_message(t('The data could not be saved, because the destination is invalid. More information is available in the system log.'), 'error');
    return FALSE;
  if ($uri = file_unmanaged_save_data($data, $destination, $replace)) {

    // Create a file object.
    $file = new stdClass();
    $file->fid = NULL;
    $file->uri = $uri;
    $file->filename = drupal_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;
    elseif ($replace == FILE_EXISTS_RENAME && is_file($destination)) {
      $file->filename = drupal_basename($destination);
    return file_save($file);
  return FALSE;


Sibiraj PR’s picture

You can use this file_save_data to save some content as file.

    $xml_name = 'test.txt'; // xml,pdf,doc etc as you needed
    $file = file_save_data($xxml,'public://' .$xml_name);
giorgio79’s picture

How can I specify encoding for this function? By default, it is saving files with ANSI encoding for me. I want utf8

prsnjtbarman’s picture

How to create the part "master_image" dynamic .. please help.

graceman9’s picture

Does $replace = FILE_EXISTS_RENAME works??
As I can see it just get basename and nothing else...

Then I get an error message below due to the fact that file already exists in {file_managed} table. Is there any "best practice" solution?
Exception caught: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://product_image/FetchFile_844.axd' for key 'uri' in /home/me/www/mysite.dev/includes/database/database.inc on line 2171.

ethan.han777’s picture

how do I add new line when file extension is .txt?
I added "\r\n" but this doesn't work.

UPDATE: please ignore this. I changed '\r\n' to "\r\n" and it works.

rameshbalda’s picture

Adding third parameter FILE_EXISTS_REPLACE works for me
file_save_data($xml,$xml_path.'/'.$object->nid.'.xml', FILE_EXISTS_REPLACE);

rameshbalda’s picture

I have faced the below error
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'public://aps/27521.xml' for key 'uri': INSERT INTO {file_managed} (uid, filename, uri, filemime, filesize, status, timestamp, type, uuid) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8); Array ( [:db_insert_placeholder_0] => 2045 [:db_insert_placeholder_1] => 27521.xml [:db_insert_placeholder_2] => public://aps/27521.xml [:db_insert_placeholder_3] => application/xml [:db_insert_placeholder_4] => 2351 [:db_insert_placeholder_5] => 1 [:db_insert_placeholder_6] => 1494852066 [:db_insert_placeholder_7] => undefined [:db_insert_placeholder_8] => 9c3277fe-8ed2-4721-9817-9ba6059fffbc ) in drupal_write_record() (line 7376 of /www/nba-drupal/core/nets/site-1770/includes/common.inc).

to fix this issue i have added FILE_EXISTS_REPLACE as third parameter as shown in below, for me the issue is fixed.
file_save_data($xml,$xml_path.'/'.$object->nid.'.xml', FILE_EXISTS_REPLACE);