Page 1 of 1

uploading files

Posted: Tue Mar 11, 2008 1:00 pm
by shiggy
Hi,
I am writing a program that uploads files onto a server. Right now I am uploading excel files. I am using html to ask for a file path, and then use php to transfer the file onto a folder in the server computer.

For security purposes, is there any way to check if the file uploaded is a valid excel file (and not just some file changed to .xls)? It doesn't have to be excel, is it possible to check if a file is a valid jpeg, bitmap, wmv, etc?

Thanks!

Re: uploading files

Posted: Tue Mar 11, 2008 1:22 pm
by Sekka
You need to check the mime type of the file.

This page lists all the mime types for an excel document.

This is easy to check when files are uploaded via forms as the mime type is stored in $_FILES['formfield']['type'], but you are copying the file to your server via a URL are you not?

As long as you are on a Apache server, you can still do a mime type check. Once the file is copied to your server, run the following,

Code: Select all

// Check the MIME if possible
if (function_exists ("shell_exec")) {
    
    // Get the MIME
    $result = @shell_exec ("file " . $filepath . " -i");
    if (is_string ($result)) {
        
        // Parse out the MIME
        $mime = substr (strrchr ($result, ":"), 1);
        $mime = substr (trim ($mime), 0, strpos ($mime, ";"));
        
        // Check the MIME type
        switch ($mime) {
            case "mime/type":
            case "anothermime/type":
                break;
            default:
                return false;
                break;  
        }
        
    }
    
}
This code gets the mime type using a server command and checks it against the required types in the switch.

Re: uploading files

Posted: Tue Mar 11, 2008 3:49 pm
by shiggy
Thanks! I never knew about mimes before, this is exactly what I needed.