我在批准上传文件时遇到问题。我希望用户只上传.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
感谢您的帮助。
答案 0 :(得分:0)
对于xml文件,$finfo->file()
似乎返回application/xml
而不是text/xml
。
使用有效的mime-types将数组更改为:
array(
'xml' => 'application/xml',
'txt' => 'text/plain',
),
答案 1 :(得分:-1)
尝试使用以下代码。文件的扩展正在代码中正确。
if(!move_uploaded_file( $ _FILES [&#39; upfile&#39;] [&#39; tmp_name&#39;],&#39;上传/&#39; .basename($ _ FILES [&#34; upfile&#34;] [& #34;名称&#34;] ) ))