Friday, July 8, 2011

File Extension Testing Module

In Drupal 6, Whenever  you try to upload a file, it checks only the extension from file name. I found this by trying this :

1)  Create a file with some HTML contents and save it as .pdf or .jpg.
2) Upload it to drupal whose allowed extensions are jpg, pdf.
3) It will upload the files. This is wrong.

To Overcome this, i have written a module which is shown below :

filevalidate.php


<?php
function filevalidateinit($node_type, $form) {
    $field_obj = $form['field_file'];
    $cnt = count($form['nid']['#post']['field_file']);
    $file_field = 'field_form_upload';
    file_upload_validation($field_obj, $cnt, $file_field);
}


common.php

<?php
function file_upload_validation($field_obj, $cnt, $field_name) {
    $finfo = finfo_open(FILEINFO_MIME, "/usr/share/misc/magic.mgc");

    if (!$finfo) {
        echo "Opening fileinfo database failed";
        exit();
    }
   
    /* get mime-type for a specific file */
    for ($i=0;$i<$cnt;$i++) {

    $filepath = $field_obj[$i]['#value']['filepath'];
    $filename = $field_obj[$i]['#value']['filename'];

    $mimetyy = finfo_file($finfo, $filepath, FILEINFO_MIME_TYPE);

    $tyy = explode("/", $mimetyy);

    $path_info = pathinfo($filepath);
    $extt = $path_info['extension'];

    if($extt === $tyy[1]) {    }
    else {
        file_set_status(&$filename, FILE_STATUS_TEMPORARY);
        //file_delete($filename);
        form_set_error($field_name, $filename." is not a ".$extt."  Format");
    }
    }
/* close connection */
finfo_close($finfo);
}


security.module
<?php
require_once('common.php');
function security_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
    switch ($op) {
        case 'validate':
                    include_once ('php/filevalidate.php');
                    filevalidateinit($node->type, $a3);


    }
}

Hope this helps you.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.