Community Documentation

file_transfer

5 file.inc file_transfer($source, $headers)
6 file.inc file_transfer($source, $headers)
7 file.inc file_transfer($uri, $headers)
8 file.inc file_transfer($uri, $headers)

Transfer file using HTTP to client.

Pipes a file through Drupal to the client.

Parameters

$uri: String specifying the file URI to transfer.

$headers: An array of HTTP headers to send along with file.

Related topics

▾ 2 functions call file_transfer()

file_download in includes/file.inc
Menu handler for private file transfers.
image_style_deliver in modules/image/image.module
Menu callback; Given a style and image path, generate a derivative.

File

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

Code

<?php
function file_transfer($uri, $headers) {
  if (ob_get_level()) {
    ob_end_clean();
  }

  foreach ($headers as $name => $value) {
    drupal_add_http_header($name, $value);
  }
  drupal_send_headers();
  $scheme = file_uri_scheme($uri);
  // Transfer file in 1024 byte chunks to save memory usage.
  if ($scheme && file_stream_wrapper_valid_scheme($scheme) && $fd = fopen($uri, 'rb')) {
    while (!feof($fd)) {
      print fread($fd, 1024);
    }
    fclose($fd);
  }
  else {
    drupal_not_found();
  }
  drupal_exit();
}
?>

Comments

Note about the headers

Note that the comment by jpwarren00 for the Drupal 6 version of this call does not apply to Drupal 7. Use an associative array, as in:
'Content-Type'  => 'application/octet-stream'
Also, for public files, the uri should be relative to the public file system path, which is sites/default/files by default.

After file_transfer() inside form submit no code is executed

<?php
function my_form_submit($form, $form_state) {

   
$headers = array(...);
   
$path_to_file = "/bla/bla/blabla";
   
file_transfer($path_to_file, $headers);
   
    
//Any code here won't be executed
     //I guess it's due to drupal_exit() inside file_transfer()
     //Help someone?

}
?>

Sub

+1. Also wondering.

Yes, either drupal_exit or

Yes, either drupal_exit or drupal_not_found is called by file_transfer dependent on the success or failure of transferring the file (you can find the function defined in includes/file.inc). I'm no authority on this, but I'm supposing the thinking is that calling file_transfer is quite a final action to take. You have to send headers followed by file content to the browser and once that's done there's nothing more you can do in terms of loading the page. Can you achieve the results you want by running your code before calling file_transfer?

Login or register to post comments