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

Submit handler to write an unmanaged file using plain PHP functions.

The key functions used here are:

Related topics

File

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

Code

function file_example_unmanaged_php_submit($form, &$form_state) {
  $data = $form_state['values']['write_contents'];
  $destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;

  if (empty($destination)) {
    // If no destination has been provided, use a generated name.
    $destination = backdrop_tempnam('public://', 'file');
  }

  // With all traditional PHP functions we can use the stream wrapper notation
  // for a file as well.
  $fp = fopen($destination, 'w');

  // To demonstrate the fact that everything is based on streams, we'll do
  // multiple 5-character writes to put this to the file. We could easily
  // (and far more conveniently) write it in a single statement with
  // fwrite($fp, $data).
  $length = strlen($data);
  $write_size = 5;
  for ($i = 0; $i < $length; $i += $write_size) {
    $result = fwrite($fp, substr($data, $i, $write_size));
    if ($result === FALSE) {
      backdrop_set_message(t('Failed writing to the file %file', array('%file' => $destination)), 'error');
      fclose($fp);
      return;
    }
  }
  $url = file_create_url($destination);
  $_SESSION['file_example_default_file'] = $destination;
  backdrop_set_message(
  t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)', 
  array(
    '%filename' => $destination,
    '@uri' => $destination,
    '!url' => l(t('this URL'), $url),
  )
  )
  );
}