【发布时间】:2016-05-01 10:23:51
【问题描述】:
我试图将文件上传限制为仅在 php 中的图像,但不允许我上传 .psd 格式的图像。如何在php中允许.psd文件上传。
现在我正在这样做
<input accept="image/*" type="file" name="image" />
【问题讨论】:
-
客户端验证没用。
我试图将文件上传限制为仅在 php 中的图像,但不允许我上传 .psd 格式的图像。如何在php中允许.psd文件上传。
现在我正在这样做
<input accept="image/*" type="file" name="image" />
【问题讨论】:
永远不要依赖客户端验证并且不信任$_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();
}
?>
【讨论】: