uploading files

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
shiggy
Forum Newbie
Posts: 2
Joined: Tue Mar 11, 2008 12:53 pm

uploading files

Post 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!
User avatar
Sekka
Forum Commoner
Posts: 91
Joined: Mon Feb 18, 2008 10:25 am
Location: Huddersfield, West Yorkshire, UK

Re: uploading files

Post 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.
shiggy
Forum Newbie
Posts: 2
Joined: Tue Mar 11, 2008 12:53 pm

Re: uploading files

Post by shiggy »

Thanks! I never knew about mimes before, this is exactly what I needed.
Post Reply