我遇到了php批准我的文件上傳的問題。我希望用戶只上傳.xml文件。但它不起作用。通過MIME的PHP文件上傳限制xml文件
這裏是我的HTML表單:
<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>
,這裏是我的PHP來控制通過MIME類型文件:
<?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();
}
?>
簡單JPG和PNG它的工作原理,但不使用XML。 我檢查了MIME類型,它仍然沒有我在Windows上使用XAMPP運行PHP
謝謝您的幫助,工作
。
你檢查過$ finfo-> file($ _ FILES ['upfile'] ['tmp_name'])'實際返回嗎? –
對不起。我是一名php lerner。我如何檢查它? – Joscha