php上传图片安全性

发布时间:2015-01-15 21:32:53 阅读:1499次

通过getimagesize取得图片的类型,将$_FILES传给$array

        function uploadPic($array){

                $rand=$this->randomkeys(8);
                $tmp_name=$array["thumb"]["tmp_name"];
                $img_type=$array["thumb"]["type"];
                $year=date("Y");
                $month=date("m");
                $day=date("d");
                if(!file_exists("uploadfile/".$year)){
                        mkdir("uploadfile/".$year);
                }
                if(!file_exists("uploadfile/".$year."/".$month.$day)){
                        mkdir("uploadfile/".$year."/".$month.$day);
                }
                $allowtype=array("image/pjpeg","image/jpg","image/jpeg","image/png","image/x-png","image/gif");
                $phpcheck=@getimagesize($tmp_name);
                if(!is_array($phpcheck)){
                        echo "not img1";
                        exit;
                }
                if(!in_array($img_type,$allowtype)){
                        echo "not1 allow img";
                        exit;
                }
                $resignname=md5($rand.time().$tmp_name);
                if($img_type=="image/jpg"||$img_type=="image/jpeg"||$img_type=="image/pjpeg"){
                        $ext=".jpg";
                }
                if($img_type=="image/png"||$img_type=="image/x-png"){
                        $ext=".png";
                }
                if($img_type=="image/gif"){
                        $ext=".gif";
                }
                $newname=$resignname.$ext;
                $newname=substr($newname,16);
                $file_dest="uploadfile/".$year."/".$month.$day."/".$newname;
                if(move_uploaded_file($tmp_name,$file_dest)){
                        $imgurl = $year."/".$month.$day."/".$newname;
                        return $imgurl;
                }
        }   

        function randomkeys($length){
                $pattern='1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
                for($i=0;$i<$length;$i++){
                        $key .= $pattern{mt_rand(0,35)};    //生成php随机数
                }
                return $key;
        }

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询

转载请注明:php上传图片安全性 出自老鄢博客 | 欢迎分享