简体   繁体   中英

detect uploaded file type using PHP

I noticed that for the same exact file, the $_FILES['file']['type'] is different depending if you are uploading from a windows client or a mac client.

I am using PHP for my server side. How can I be absolutely sure of the file type?

There have been some answers given for eg : https://stackoverflow.com/a/6755263/80353

I want to make it explicit the best way I have found for this to work.

1) Install finfo library

http://us1.php.net/manual/en/fileinfo.installation.php

2) Use the finfo functions on the $_FILES['file']['tmp_name']

Below is a function I use to detect for zip file.

/**
 * Detect from the $_FILES['file'] array
 *
 * @param Array $data is the $_FILES['file']  array
 * @return boolean Return true if uploaded file is a zip file
 */
public function isZip($data = null) {
    if ($data == null) {
       $data = $_FILES['file'];
    }
    $tmpname = $data['tmp_name'];
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimetype = finfo_file($finfo, $tmpname);
    if($mimetype == 'application/zip') {
        return true;
    }
    return false;
}

I put this up hopefully to prevent other PHP developers from making the same mistake I did and spending 2 hours on the troubleshooting.

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