1 file_example.module | file_example_unmanaged_write_submit($form, &$form_state) |
Submit handler to write an unmanaged file.
The key functions used here are:
- file_unmanaged_save_data(), which takes a buffer and saves it to a named file, but does not create any kind of tracking record in the database. This example uses FILE_EXISTS_REPLACE for the third argument, meaning that if there's an existing file at this location, it should be replaced.
- file_create_url(), which converts a URI in the form public://junk.txt or private://something/test.txt into a URL like http://example.com/sites/default/files/junk.txt.
Related topics
File
- modules/
examples/ file_example/ file_example.module, line 232 - Hook implementations for the File Example module.
Code
function file_example_unmanaged_write_submit($form, &$form_state) {
$data = $form_state['values']['write_contents'];
$destination = !empty($form_state['values']['destination']) ? $form_state['values']['destination'] : NULL;
// With the unmanaged file we just get a filename back.
$filename = file_unmanaged_save_data($data, $destination, FILE_EXISTS_REPLACE);
if ($filename) {
$url = file_create_url($filename);
$_SESSION['file_example_default_file'] = $filename;
backdrop_set_message(
t('Saved file as %filename (accessible via !url, uri=<span id="uri">@uri</span>)',
array(
'%filename' => $filename,
'@uri' => $filename,
'!url' => l(t('this URL'), $url),
)
)
);
}
else {
backdrop_set_message(t('Failed to save the file'), 'error');
}
}