我试图仅在php中限制文件上传到图像,但不允许我上传.psd格式的图像。如何在php中允许. psd文件上传。
现在我正在这样做
<input accept="image/*" type="file" name="image" />
答案 0 :(得分:2)
永远不要依赖客户端验证和不信任 $_FILES['upfile']['mime']
值!!
您需要检查psd
文件的以下mime类型,并根据您的情况进行一些修改:
'psd' => 'image/psd',
'psd' => 'image/x-photoshop',
'psd' => 'application/photoshop',
'psd' => 'zz-application/zz-winassoc-psd',
'psd' => 'application/psd'
来自php手册Handling file uploads:
<?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['image']['error']) ||
is_array($_FILES['image']['error'])
) {
throw new RuntimeException('Invalid parameters.');
}
// Check $_FILES['image']['error'] value.
switch ($_FILES['image']['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.');
}
// DO NOT TRUST $_FILES['image']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['image']['tmp_name']),
array(
'psd' => 'image/psd',
'psd' => 'image/x-photoshop',
'psd' => 'application/photoshop',
'psd' => 'zz-application/zz-winassoc-psd',
'psd' => 'application/psd'
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['image']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['image']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['image']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>