Search code examples
phpxmluploadxamppmime

php file upload restriction for xml files via mime


I'm having a problem with php approving my file upload. I want the user to only upload .xml files. But it doesn't work.

Here is my html form:

<form action="upload2.php" method="post" enctype="multipart/form-data">
    Wähle deine Sprachdatei aus:
    <input type="file" class="form-control-file" name="upfile">
    <br>
    <input type="submit" class="btn btn-primary" value="Sprachdatei hochladen" name="submit">
</form>

and here is my php to control the file via MIME type:

<?php
header('Content-Type: text/plain; charset=utf-8');
try {

// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if (
    !isset($_FILES['upfile']['error']) ||
    is_array($_FILES['upfile']['error'])
) {
    throw new RuntimeException('Invalid parameters.');
}

// Check $_FILES['upfile']['error'] value.
switch ($_FILES['upfile']['error']) {
    case UPLOAD_ERR_OK:
        break;
    case UPLOAD_ERR_NO_FILE:
        throw new RuntimeException('No file sent.');
    case UPLOAD_ERR_INI_SIZE:
    case UPLOAD_ERR_FORM_SIZE:
        throw new RuntimeException('Exceeded filesize limit.');
    default:
        throw new RuntimeException('Unknown errors.');
}

// You should also check filesize here.
if ($_FILES['upfile']['size'] > 1000000) {
    throw new RuntimeException('Exceeded filesize limit.');
}

// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
        $finfo->file($_FILES['upfile']['tmp_name']),
        array(
            'xml' => 'text/xml',
            'txt' => 'text/plain',

        ),
        true
    )) {
    throw new RuntimeException('Invalid file format.');
}

// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
    $_FILES['upfile']['tmp_name'],
    sprintf('./uploads/%s.%s',
        sha1_file($_FILES['upfile']['tmp_name']),
        $ext
    )
)) {
    throw new RuntimeException('Failed to move uploaded file.');
}

echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>

with simple jpg and png it works but not with xml. I checked the MIME Type and it's still not working

I'm using XAMPP on Windows to run php


Solution

  • It seems like $finfo->file() returns application/xml instead of text/xml for xml files.

    Change your array with valid mime-types to this:

    array(
        'xml' => 'application/xml',
        'txt' => 'text/plain',
    ),