I'm using filefield module, and it has permitted extension field. Is it possible to disallow certain extensions (e.g. exe, zip, rar) instead of adding permissions for ones that are ok?
1 Answer
Not directly, but you could do that in your own custom form validation. For example:
function YOURMODULE_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'YOUR_CONTENT_TYPE_node_form':
$form['#validate'][]='YOURMODULE_valid_extensions';
break;
// any other forms here
}
// any other form alters here
}
function YOURMODULE_valid_extensions($form, &$form_state) {
// $whitelist=array('txt', 'doc', 'pdf');
$blacklist=array('xxx', 'exe', 'php');
/* I am assuming that this is a single value field ([0] below) */
$extension=pathinfo($form_state['values']['field_YOURFIELD'][0]['filename'], PATHINFO_EXTENSION);
// if (in_array($extension, $whitelist)) {
// return;
// }
if (in_array($extension, $blacklist)) {
form_set_error('field_YOURFIELD', t('Invalid file extension'));
}
}
and if you leave the extensions field blank, filefield won't do any validation, but you will in the second function above. I've also put in //'s
basically what filefield is doing if you wanted to incorporate both. If you do go this route, you will have to put some verbiage in your help section as the widget will most probably say all extensions are valid :)
-
Thanks man. Your code seem logical to me, but for some reason, it doesn't work. It adds #validation in form, but MY_MODULE_valid_extensions is having some troubles. Filefield permission is set empty and uploading exe files is successful even though it's blacklisted. Aug 21, 2012 at 19:52
-
make sure you have changed 'field_YOURFIELD' to whatever your field name is. (a drupal_set_message('<pre>' . print_r($form_state['values'], true) . '</pre>'); will show you all of them) Aug 21, 2012 at 20:05
-
-
Odd. It works here, and I cut/pasted everything from above to make sure I didn't have a cut/paste error in there and the only thing I changed was 'field_YOURFIELD' to 'field_file_upload' which is the exact field name here on my test box. Aug 21, 2012 at 20:31
-
Now, I should say is it does allow you to upload the file via AJAX/AHAH, but it won't allow you to actually save the node. So, you definitely want a help message telling your users they will waste a lot of time uploading a 32mb exe file only to be told 'Invalid extension' after doing so :) Aug 21, 2012 at 20:32