3

I have troubles with Drupal 7 and file uploading.

My code that doesn't work:

function test_form($form, &$form_state){

$form['#attributes'] = array('enctype' => "multipart/form-data");
$form['podcast'] = array(
    '#title' => 'Audio file',
    '#type' => 'file',
);
$form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
);
return $form;

}

function test_form_submit($form, &$form_state){

$vals = $form_state['values'];
$filepath = 'public://test/';
//$filepath = 'temporary://test/';
$filename = 'rcc_date.mp3';

file_prepare_directory($filepath, FILE_CREATE_DIRECTORY);
$file = file_save_upload('podcast', array('file_validate_extensions' => array()), $filepath.$filename);
//got FALSE here. Why?
die(print_r($file===FALSE).'-');

}

So path created but file doesn't uploads and file_save_upload returns FALSE. Also I tried array() and true as $validators with no effect.

Any help greatly appreciated. Thanks.

3
  • How to get the filename dynamically ? Commented Mar 26, 2014 at 5:05
  • The filename is completely unnecessary in this code. Leave it out completely. Don't set the $filename variable, and don't append it to $filepath. Commented Dec 3, 2015 at 17:54
  • To use an empty array of file validators, like array('file_validate_extensions' => array()), is unsafe and shouldn't be used. Use NULL instead, to take the default, or make a real list yourself. See the note in api.drupal.org/api/drupal/includes!file.inc/function/… Commented Dec 3, 2015 at 17:59

1 Answer 1

4

Doh. $destination shouldn't contain filename, just path.

Sign up to request clarification or add additional context in comments.

1 Comment

For those of you wondering where $destination is, it's the third argument to file_save_upload. That line should look like this: $file = file_save_upload('podcast', array('file_validate_extensions' => array()), $filepath); Or preferably, like this: $file = file_save_upload('podcast', null, $filepath); This is a lot more secure. It doesn't allow PHP files, for example, to be uploaded, which would be a huge security risk. See api.drupal.org/api/drupal/includes!file.inc/function/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.