function isImage($filename){
$types = '.jpeg|.png|.gif';
if(file_exists($filename)){
$info = getimagesize($filename);
$ext = image_type_to_extension($info[2]);
if(stripos($types,$ext)>=0){
return $ext;
}else{
return false;
}
}else{
return false;
}
}
$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
$temp_file = $_FILES['upload_file']['tmp_name'];
$res = isImage($temp_file);
if(!$res){
$msg = "文件未知,上传失败!";
}else{
$img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").$res;
if(move_uploaded_file($temp_file,$img_path)){
$is_upload = true;
} else {
$msg = "上传出错!";
}
}
}
其实和14题没什么区别,就是从只读取图片的两个字节变成了getimagesize()检查是否为图片文件!
参考其他博主的验证代码:
<?php
$remote_png_url = 'C:/users/tutub/desktop/up/test.jpg';
$img_data = getimagesize($remote_png_url);
print_r($img_data );
?>
Array
(
[0] => 1054 //索引 0 给出的是图像宽度的像素值
[1] => 241 //索引 1 给出的是图像高度的像素值
[2] => 2 //索引 2 给出的是图像的类型,返回的是数字,其中1 = GIF,2 = JPG,3 = PNG,4 = SWF,5 = PSD,6 = BMP,7 = TIFF(intel byte order),8 = TIFF(motorola byte order),9 = JPC,10 = JP2,11 = JPX,12 = JB2,13 = SWC,14 = IFF,15 = WBMP,16 = XBM
[3] => width="1054" height="241" //索引 3 给出的是一个宽度和高度的字符串,可以直接用于 HTML 的 <image> 标签
[bits] => 8 //索引 bits 给出的是图像的每种颜色的位数,二进制格式
[channels] => 3 //索引 channels 给出的是图像的通道值,RGB 图像默认是 3
[mime] => image/jpeg //索引 mime 给出的是图像的 MIME 信息,此信息可以用来在 HTTP Content-type 头信息中发送正确的信息,如: header("Content-type: image/jpeg");
)
所以这里直接传图片马也是OK的。