【发布时间】:2013-05-14 07:06:26
【问题描述】:
我有一个 file-type 验证来检查 image 扩展。
但是,当我尝试上传诸如 .exe 或 .mp3 之类的文件以及允许的扩展名之外的几乎任何内容时:
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
它随机工作,我的意思是,有时它会回显错误,有时错误不会被回显。
这是检查扩展名的行.... thingy
if (in_array($image_ext, $allowed_ext) === false){
$errors[] = '<font color="red">*File type is not allowed.</font>';
}
完整代码:
if (isset($_FILES['image'], $_POST['album_id'])){
$image_name = $_FILES['image']['name'];
$image_size = $_FILES['image']['size'];
$image_temp = $_FILES['image']['tmp_name'];
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
//seperate thingies
$tmp = explode('.', $image_name);
$image_ext = strtolower(end($tmp));
$album_id = $_POST['album_id'];
//error array
$errors = array();
if (empty($image_name)){
$errors[] = '<font color="red">*Please choose a photo.</font>';
}
if (empty($album_id)){
$errors[] = '<font color="red">Invalid album.</font>';
} else {
// not allowed extension?
if (!$allowed_ext){
$errors[] = '<font color="red">*The file type is not supported</font>';
}
if (in_array($image_ext, $allowed_ext) === false){
$errors[] = '<font color="red">*File type is not allowed.</font>';
}
// 5 MB file
if ($image_size > 5242880 ){
$errors[] = '<font color="red">*Maximum file size is 2MB.</font>';
}
if (album_check($album_id) === false){
$errors[] = '<font color="red">*Couldn\'t upload to that album.</font>';
}
// puting this in here prevent undefined index error.
$caption = $_POST['caption'];
if (empty($caption)){
$errors[] = '<font color="red">*Caption cannot be empty</font>';
}
}
// check if error, if error, echo errors
if (!empty($errors)){
foreach ($errors as $error){
echo $error, '<br />';
}
} else {
// upload the image if no error
upload_image($image_temp, $image_ext, $album_id);
header('Location: view_album.php?album_id='.$album_id);
exit();
}
【问题讨论】:
-
当你只检查一个时,你为什么要检查它是否为假......如果没有必要
-
需要您的完整代码。也希望您明白,仅通过扩展名检查文件并不是防止恶意代码上传的万无一失的方法。
-
你把图片扩展和尺寸验证放在
else -
尝试修剪(strtolower(end($tmp)))
-
为什么没有其他人对
font标签感到惊讶?
标签: php image file validation