使用扩展名检查文件类型通常是一个坏习惯。我可以轻松创建一个文本文件并将其重命名为.jpg根据此代码,它会突然变为实际图像。或者更加邪恶:我可能会通过创建一个实际执行一些代码的假jpg来利用webbrowsers中的一些错误。
除此之外,我可能会命名我的jpeg文件JPEG,jPG,jpG,JPeg或任何其他你可能会想到的组合。然后还有其他格式,而不是jpeg。我不知道你的其他代码,但也许你想让别人上传png或gif图片。
如果你想更确定你确实有图像文件,更确定的方法是使用getimagesize。这确实需要GD扩展。如果该功能为您提供了看起来可能是真实的输出,那么使用该文件作为图像会更安全。当然,有些情况下你不关心,只想检查文件的扩展名。但我觉得这个代码应该公开一点。一个小例子:
<?php
$file = $row['dfilepath'];
// where upload_dir is a function that somehow finds
// the absolute path of the upload dir
$path = upload_dir() . DIRECTORY_SEPARATOR . $file;
$valid = array('image/jpeg', 'image/gif', 'image/png');
$info = getimagesize($path);
if($info !== false && in_array($info['mime'], $valid) {
// more likely you'll actually have an image here
// now you might want to print some html here, like:
?><img src="/uploads/<?php print $file; ?>" alt="" /><?php
}
?>
请参阅我的编辑问题... – udaya 2010-01-22 13:43:08