您最好彻底检查 $_FILES 结构和值。
以下代码绝对不会导致任何错误。
示例
<?php
header('Content-Type: text/plain; charset=utf-8');
try {
if (
!isset($_FILES['upfile']['error']) ||
is_array($_FILES['upfile']['error'])
) {
throw new RuntimeException('无效参数。');
}
switch ($_FILES['upfile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new RuntimeException('没有发送文件。');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new RuntimeException('超出文件大小限制。');
default:
throw new RuntimeException('未知错误。');
}
if ($_FILES['upfile']['size'] > 1000000) {
throw new RuntimeException('超出文件大小限制。');
}
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('无效的文件格式。');
}
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('无法移动上传的文件。');
}
echo '文件已成功上传。';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>