php文件上传

< form  action= "int.php"  method= "post"  enctype= "multipart/form-data" >
     < caption > 文件上传 </ caption >
     < table >
       < tr >
         < td >请选择头像: </ td >
         < td >< input  type= "file"  name= "user_pic" ></ td >
       </ tr >
       < tr >
         < td >< input  type= "submit"  value= "提交" ></ td >
       </ tr >
     </ table >


   </ form >

<?php
$desc= 'upload/';
$maxsize= 20* 1024;
if( $_FILES[ 'user_pic'][ 'size']> $maxsize){
   echo  '图片太大,服务器撑不下';
   exit;
}

$ext= strrchr( $_FILES[ 'user_pic'][ 'name'], '.');
$filename= uniqid( 'tn_', true);



通常都是按照日期来分组
$sub_path= date( 'Ymd'). '/';
if(! is_dir( $desc. $sub_path)){ //先判断是否有该文件
   mkdir( $desc. $sub_path, 0777, true); //创建这个文件夹
}
$desc.= $sub_path. $new_name;
此时一般还要限制上传的文件类型
$allow_type= array( 'image/jepg', 'image/jpg', 'image/png', 'image/gif');
$true_type= $_FILES[ 'user_pic'][ 'type'];
if(! in_array( $true_type, $allow_type)){
   echo  '不支持该文件类型';
   exit;
}

还有个问题  就是防excel其他文件混杂在一起  上传,使用finfo对象
实例化
$finfo=new finfo(FILEINFO_MIME_TYPE);
$type=$finfo->file( $_FILES [ 'user_pic' ][ 'tmp_name' ]); //它会返回一个真实文件名

if(!in_array($type,$allow_type)){
echo '不支持该类型文件';
exit;
}


$new_name= $filename. $ext;
$desc.= $new_name;
if( move_uploaded_file( $_FILES[ 'user_pic'][ 'tmp_name'], $desc)){
   echo  '上传成功';
} else{
   echo  '上传失败';
}                                    
一般在项目中使用 则需要面向对象方法
class  upload{
private  $upload_path= 'uploads/';
private  $maxsize= 200* 1024;
private  $prefix= 'tn_';
private  $allow_type= array( 'image/jepg', 'image/jpg', 'image/png', 'image/gif');

public  function  __set( $p, $v){
   if( property_exists( $this, $p)){
     $this-> $p= $v;
  }
}

public  function  __get( $p){
return  $this-> $p;
}
public  function  doUpload( $file){
$desc= $this-> upload_path;
$maxsize= $this-> maxsize;
if( $file[ 'size']> $maxsize){
   echo  '图片太大,服务器撑不下';
   exit;
}
$filename= uniqid( $this-> prefix, true);
$ext= strrchr( $file[ 'name'], '.');
$new_name= $filename. $ext;
$sub_path= date( 'Ymd'). '/';
if(! is_dir( $desc. $sub_path)){
   mkdir( $desc. $sub_path, 0777, true);
}
$desc.= $sub_path. $new_name;
//上传的文件是否支持
$allow_type=this-> allow_type;
$true_type= $file[ 'type'];
if(! in_array( $true_type, $allow_type)){
   echo  '不支持该文件类型';
   exit;
}
$finfo= new  finfo(FILEINFO_MIME_TYPE);
$type= $finfo->file( $file[ 'tmp_name']);  //它会返回一个真实文件名

if(! in_array( $type, $allow_type)){
echo  '不支持该类型文件'
exit;
}
if( move_uploaded_file( $file[ 'tmp_name'], $desc)){
   echo  '上传成功';
} else{
   echo  '上传失败';
}

}


}
$upload=new Upload();
$path=$upload->doUpload($_FILES['cat_logo']);
var_dump($path);



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值