Skip to content

Instantly share code, notes, and snippets.

@Sleavely
Last active January 3, 2016 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sleavely/8399813 to your computer and use it in GitHub Desktop.
Save Sleavely/8399813 to your computer and use it in GitHub Desktop.
Drupal 7 form file processing
<?php
function mymodule_form($form, &$form_state) {
// [...]
$form['attachment'] = array(
'#type' => 'file',
'#title' => t('Attachment'),
);
// [...]
}
function mymodule_form_validate(&$form, &$form_state) {
// [...]
// If a file was attached, validate its size and remember that it exists.
$megabytes = 25;
$file_validators = array(
'file_validate_size' => array(($megabytes*1024*1024)),
"file_validate_extensions" => array("7z ai bmp doc docx eml eps gif gz jpeg jpg log pdf png pps ppsx ppt pptx psd rtf sql tif txt xls xlsx xml zip")
);
// Save the file as a temporary file.
$file = file_save_upload('attachment', $file_validators);
if ($file === FALSE) {
form_set_error('attachment', t('Your file is either too big or using a disallowed file extension.'));
}
elseif ($file !== NULL) {
$form_state['values']['attachment'] = $file;
}
// [...]
}
function mymodule_form_submit(&$form, &$form_state) {
// [...]
$has_attachment = !empty($form_state['values']['attachment']);
if($has_attachment) {
$filepath = drupal_realpath($form_state['values']['attachment']->uri);
_mymodule_dosomething_with_a_file($filepath);
}
// [...]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment