首先,关于文件上传的重要注意事项:type
和name
键使用不安全。这是因为它们是由客户端定义的,并且它们是将恶意代码注入您的站点的潜在机制。考虑一下如果我将文件名设置为../../../../../index.php
,或者如果我将 MIME 类型设置为image/gif
但上传了一个 PHP 文件会发生什么?
接下来,关于图片上传的一个重要说明:您不能信任客户端上传的图片数据。也可以在看起来像图像的东西中嵌入恶意代码。您需要从文件中复制像素数据并创建一个新的。这通常通过 GD 扩展来完成。
接下来,on mkdir()
- 它有第三个参数,如果你传递true
给第三个参数,它会递归地创建目录树,所以你不需要在单独的操作中创建每个级别。另请注意,(像许多事情一样)可能mkdir()
会失败,如果发生这种情况它将返回false
,您应该检查这一点。
现在,为了回答实际问题(暂时忽略前面提到的安全问题),我将如何简化您的代码:
// Configuration
$allowedTypes = array(
"image/gif", "image/jpeg", "image/png", "image/pjpeg"
);
$baseDir = './uploads';
// Check file was uploaded successfully
if ($_FILES['image_name']['error'] > 0) {
exit('Return Code: ' . $_FILES['image_name']['error'] . '<br />');
}
// Check file type
if (!in_array($_FILES["image_name"]["type"], $allowedTypes)) {
exit('Invalid file type: ' . $_FILES['image_name']['type'] . '<br />');
}
// Check/create target directory
list($year, $month, $day) = explode('-', date('y-m-d'));
$targetDir = $baseDir . '/' . $year . '/' . $month . '/' . $day;
if (!is_dir($targetDir)) {
if (!mkdir($targetDir, 0644, true)) {
exit('Failed to create destination directory<br />');
}
}
// Store the uploaded file permanently
$targetPath = $targetDir . '/' . .$_FILES['image_name']['name'];
if (!move_uploaded_file($_FILES['image_name']['tmp_name'], $targetPath)) {
exit('Failed to move temporary file<br />');
}
但是,我不会这样做。
文件上传是一项非常常见的任务,我使用的通用代码看起来像这样。看起来很复杂是不是?嗯,那是因为处理文件上传并不简单。然而,这种复杂性提供了一种很好的直接方法来解决我上面概述的安全问题。它内置了对图像的支持,包括以干净简单的方式调整大小的选项。
让我们看看我们如何在您的代码中使用它:
$baseDir = './uploads';
// Very simple autoloader for demo purposes
spl_autoload_register(function($class) {
require strtolower(basename($class)).'.php';
});
// When you instantiate this the $_FILES superglobal is destroyed
// You must access all uploaded files via this API from this point onwards
$uploadManager = new \Upload\Manager;
// Fetches a FileCollection associated with the named form control
$control = $uploadManager->getControl('image_name');
// getControl returns NULL if there are no files associated with that name
if (!isset($control)) {
exit('No file was uploaded in the image_name control');
}
// Check/create target directory
// You still need to do this, it's not magic ;-)
list($year, $month, $day) = explode('-', date('y-m-d'));
$targetDir = $baseDir . '/' . $year . '/' . $month . '/' . $day;
if (!is_dir($targetDir)) {
if (!mkdir($targetDir, 0644, true)) {
exit('Failed to create destination directory');
}
}
// This also handles multiple uploads in a single control, so we need to loop
foreach ($control as $image) {
// You need to determine a file name to use, most likely not from user
// input. This is a high-entropy low collision-risk random approach.
$targetFile = $targetDir . '/' . uniquid('upload-', true);
try {
$image->save($targetFile, true, IMAGETYPE_ORIGINAL);
} catch (\Exception $e) {
exit("Oh noes! Something went badly wrong: ".$e->getMessage());
}
}
这在后台做了很多事情来解决我之前概述的安全问题。它会自动检测图像是有效的、可识别的类型,并将正确的文件扩展名应用于保存的文件。