1 file_example.module file_example_read_submit($form, &$form_state)

Submit handler for reading a stream wrapper.

Backdrop now has full support for PHP's stream wrappers, which means that instead of the traditional use of all the file functions ($fp = fopen("/tmp/some_file.txt");) far more sophisticated and generalized (and extensible) things can be opened as if they were files. Backdrop itself provides the public:// and private:// schemes for handling public and private files. PHP provides file:// (the default) and http://, so that a URL can be read or written (as in a POST) as if it were a file. In addition, new schemes can be provided for custom applications, as will be demonstrated below.

Here we take the stream wrapper provided in the form. We grab the contents with file_get_contents(). Notice that's it's as simple as that: file_get_contents("http://example.com") or file_get_contents("public://somefile.txt") just works. Although it's not necessary, we use file_unmanaged_save_data() to save this file locally and then find a local URL for it by using file_create_url().

Related topics


modules/examples/file_example/file_example.module, line 328
Examples demonstrating the backdrop File API (and Stream Wrappers).


function file_example_read_submit($form, &$form_state) {
  $uri = $form_state['values']['fileops_file'];

  if (!is_file($uri)) {
    backdrop_set_message(t('The file %uri does not exist', array('%uri' => $uri)), 'error');

  // Make a working filename to save this by stripping off the (possible)
  // file portion of the streamwrapper. If it's an evil file extension,
  // file_munge_filename() will neuter it.
  $filename = file_munge_filename(preg_replace('@^.*/@', '', $uri), '', TRUE);
  $buffer = file_get_contents($uri);

  if ($buffer) {
    $sourcename = file_unmanaged_save_data($buffer, 'public://' . $filename);
    if ($sourcename) {
      $url = file_create_url($sourcename);
      $_SESSION['file_example_default_file'] = $sourcename;
      t('The file was read and copied to %filename which is accessible at !url', 
        '%filename' => $sourcename,
        '!url' => l($url, $url),
    else {
      backdrop_set_message(t('Failed to save the file'));
  else {
    // We failed to get the contents of the requested file.
    backdrop_set_message(t('Failed to retrieve the file %file', array('%file' => $uri)));