简体   繁体   中英

PHP File Type Validation

I wrote the following php function to upload files but I'm having a hard time with the array of allowed file types. If I assign just one file type ie image/png, it works fine. If I assign more than one, its not working. I use the in_array() function to determine the allowed file types but I can't figure out how to use it properly.

Thank you!

function mcSingleFileUpload($mcUpFileName, $mcAllowedFileTypes, $mcFileSizeMax){
    if(!empty($mcUpFileName)){

        $mcIsValidUpload = true;

        // upload directory
        $mcUploadDir = UPLOAD_DIRECTORY;

        // current file properties
        $mcFileName = $_FILES[$mcUpFileName]['name'];
        $mcFileType = $_FILES[$mcUpFileName]['type'];
        $mcFileSize = $_FILES[$mcUpFileName]['size'];
        $mcTempFileName = $_FILES[$mcUpFileName]['tmp_name'];
        $mcFileError = $_FILES[$mcUpFileName]['error'];

        // file size limit
        $mcFileSizeLimit = $mcFileSizeMax;

        // convert bytes to kilobytes
        $mcBytesInKb = 1024;
        $mcFileSizeKb = round($mcFileSize / $mcBytesInKb, 2);

        // create array for allowed file types
        $mcAllowedFTypes = array($mcAllowedFileTypes);

        // create unique file name
        $mcUniqueFileName = date('m-d-Y').'-'.time().'-'.$mcFileName;

        // if file error
        if($mcFileError > 0)
        {
            $mcIsValidUpload = false;
            mcResponseMessage(true, 'File error!');
        }

        // if no file error
        if($mcFileError == 0)
        {
            // check file type
            if( !in_array($mcFileType, $mcAllowedFTypes) ){
                $mcIsValidUpload = false;
                mcResponseMessage(true, 'Invalid file type!');
            }

            // check file size
            if( $mcFileSize > $mcFileSizeLimit ){
                $mcIsValidUpload = false;
                mcResponseMessage(true, 'File exceeds maximum limit of '.$mcFileSizeKb.'kB');
            }

            // move uploaded file to assigned directory
            if($mcIsValidUpload == true){
                if(move_uploaded_file($mcTempFileName, $mcUploadDir.$mcUniqueFileName)){
                    mcResponseMessage(false, 'File uploaded successfully!');
                }
                else{
                    mcResponseMessage(true, 'File could not be uploaded!');
                }
            }
        }
    }
}
//mcRequiredFile('mcFileUpSingle','please select a file to upload!');
mcSingleFileUpload('mcFileUpSingle', 'image/png,image/jpg', 2097152);

Don't rely on the clent file type from $_FILES which is unsafe, get it from the file content.

Then define your allowed file types, check if the upload file type in your white list.

if(in_array(mime_type($file_path),$allowed_mime_types)){
    // save the file
}

$allowed_mime_types = array(
        'image/jpeg',
        'image/jpg',
        'image/png',
        'image/gif',
        'video/mp4'
);


/*
For PHP>=5.3.0, you can use php's `finfo_file`([finfo_file](https://www.php.net/manual/en/function.finfo-file.php)) function to get the file infomation about the file.

For PHP<5.3.0, you can use your's system's `file` command to get the file information.
*/
function mime_type($file_path)
{
    if (function_exists('finfo_open')) {            
        $finfo = new finfo(FILEINFO_MIME_TYPE, null);
        $mime_type = $finfo->file($file_path);
    }
    if (!$mime_type && function_exists('passthru') && function_exists('escapeshellarg')) {
        ob_start();
        passthru(sprintf('file -b --mime %s 2>/dev/null', escapeshellarg($file_path)), $return);
        if ($return > 0) {
            ob_end_clean();
            $mime_type = null;
        }
        $type = trim(ob_get_clean());
        if (!preg_match('#^([a-z0-9\-]+/[a-z0-9\-\.]+)#i', $type, $match)) {
            $mime_type = null;
        }
        $mime_type = $match[1];
    }
    return $mime_type;
}

Change this line:

$mcAllowedFTypes = array($mcAllowedFileTypes);

To this:

$mcAllowedFTypes = explode(',',$mcAllowedFileTypes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM