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

Submit handler to delete a file.

Related topics

File

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

Code

function file_example_delete_submit($form, &$form_state) {

  $uri = $form_state['values']['fileops_file'];

  // Since we don't know if the file is managed or not, look in the database
  // to see. Normally, code would be working with either managed or unmanaged
  // files, so this is not a typical situation.
  $file_object = file_example_get_managed_file($uri);

  // If a managed file, use file_delete().
  if (!empty($file_object)) {
    file_delete($file_object->fid);
    // File delete has no return; see https://github.com/backdrop/backdrop-issues/issues/652
    // so we check if the file was deleted by trying to load it.
    $not_deleted = file_load($file_object->fid);
    if ($not_deleted) {
      backdrop_set_message(t('Failed deleting managed file %uri', array('%uri' => $uri, 'error')));
    }
    else {
      backdrop_set_message(t('Successfully deleted managed file %uri', array('%uri' => $uri)));
      $_SESSION['file_example_default_file'] = $uri;
    }
  }
  // Else use file_unmanaged_delete().
  else {
    $result = file_unmanaged_delete($uri);
    if ($result !== TRUE) {
      backdrop_set_message(t('Failed deleting unmanaged file %uri', array('%uri' => $uri, 'error')));
    }
    else {
      backdrop_set_message(t('Successfully deleted unmanaged file %uri', array('%uri' => $uri)));
      $_SESSION['file_example_default_file'] = $uri;
    }
  }
}