file_save_data

5 file.inc file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
6 file.inc file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME)
7 file.inc file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)
8 file.inc file_save_data($data, $destination = NULL, $replace = FILE_EXISTS_RENAME)

Save a string to the specified destination.

Parameters

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

$dest A string containing the destination location.:

$replace Replace behavior when the destination file already exists.:

Return value

A string containing the resulting filename or 0 on error

Related topics

5 calls to file_save_data()

File

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

Code

function file_save_data($data, $dest, $replace = FILE_EXISTS_RENAME) {
  $temp = file_directory_temp();
  // On Windows, tempnam() requires an absolute path, so we use realpath().
  $file = tempnam(realpath($temp), 'file');
  if (!$fp = fopen($file, 'wb')) {
    drupal_set_message(t('The file could not be created.'), 'error');
    return 0;
  }
  fwrite($fp, $data);
  fclose($fp);

  if (!file_move($file, $dest, $replace)) {
    return 0;
  }

  return $file;
}

Comments

Dumping Arrays for Inspection

I've found one way to inspect the structure of an array that isn't detailed in documentation is to have it dumped to a file via output buffering and using file_save_data. A similar approach could be used for pretty much any other PHP-based platform, though how you save the file will differ from platform to platform.

Just stick this anywhere after the array you want to check is populated...

<?php
ob_start
();
$print_r($some_array_I_want_to_inspect);
$array_out = ob_get_contents();
ob_end_clean();
file_save_data($array_out, 'array.txt', FILE_EXISTS_REPLACE);
?>

...and the array dump will be in your site's filesystem as array.txt (e.g. sites/default/files/array.txt).

That may have some use cases.

That may have some use cases. Normally, you can simply dump variables as watchdog log entries by simply doing something like the following -

watchdog('Some identifier', 'Dumping variable - !var', array('!var' => print_r($var, 1)), WATCHDOG_NOTICE);

Much

Much better
http://drupal.org/project/devel

Just output the array with dpm

Destination

is not the folder - it must be the filepath.
Here a snippet to load a remote-Image from $fileURL into Drupal-Temp-Folder:

  $filename = basename($fileURL);
  $request = drupal_http_request($fileURL); // load file into RAM
  if ($image = $request->data) {
    $filepath = file_directory_temp().'/'.$filename;
    file_save_data($image, $filepath);
   ...
  }

Login or register to post comments