好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

php实现文件上传的程序代码 - php上传下载

php实现文件上传的程序代码

本文章来给初学者介绍一个简单的php实现文件上传的程序代码,大家可拿下去供学习使用,如果放到网络上应用我们需要更多过滤来判断了。

先来看实例

<?php                      //判断临时文件存放路径是否包含用户上传的文件            if ( is_uploaded_file ( $_FILES [ "uploadfile" ][ "tmp_name" ])){            //为了更高效,将信息存放在变量中            $upfile = $_FILES [ "uploadfile" ]; //用一个数组类型的字符串存放上传文件的信息            //print_r($upfile);//如果打印则输出类似这样的信息Array ( [name] => m.jpg [type] => image/jpeg [tmp_name] => C:WINDOWSTempphp1A.tmp [error] => 0 [size] => 44905 )            $name = $upfile [ "name" ]; //便于以后转移文件时命名            $type = $upfile [ "type" ]; //上传文件的类型            $size = $upfile [ "size" ]; //上传文件的大小            $tmp_name = $upfile [ "tmp_name" ]; //用户上传文件的临时名称            $error = $upfile [ "error" ]; //上传过程中的错误信息            //echo $name;            //对文件类型进行判断,判断是否要转移文件,如果符合要求则设置$ok=1即可以转移            switch ( $type ){                case   "image/jpg" :  $ok =1;                break ;                case   "image/jpeg" :  $ok =1;                break ;                case   "image/gif"  :  $ok =1;                break ;                default : $ok =0;                break ;           }            //如果文件符合要求并且上传过程中没有错误            if ( $ok && $error == '0' ){                //调用move_uploaded_file()函数,进行文件转移               move_uploaded_file( $tmp_name , 'up/' . $name );                //操作成功后,提示成功                echo   "<script language=" javascript ">alert('succeed')</script>" ;           } else {                //如果文件不符合类型或者上传过程中有错误,提示失败                echo   "<script language=" javascript ">alert('failed')</script>" ;           }       }   ?>   <!--设置提交文件的表单-->   <form enctype= "multipart/form-data"  method= "post"  name= "uploadform" >   <input type= "file"  name= "uploadfile"  value= "Upload File" >   <input type= "submit"  name= "submit"  value= "Upload" >   </form> 

上面的代码完全可以工作,但实际应用中漏洞百出,让我们逐步来完善之首先,上载的文件必须有一个固定的目录保存,我们在这里用一个$UploadPath变量保存之,如$UploadPath = "/home/flier/upload/"; 或复杂一点的自动定位,如

$UploadPath  =  AddSlashes (dirname( $PATH_TRANSLATED )). "\upload\" ; 

$PATH_TRANSLATED顾名思义是当前传送目录

我们假定以其一个名为upload的子目录来保存上载的文件。dirname函数返回其目录名,然后加上子目录名然后用一个变量$FileName保存完整的上载后文件名和路径 $FileName = $UploadPath.$UploadFile_name;

其次,我们还想让用户得知上载文件的简要信息,如上载文件的大小if($UploadFile_size <1024) {  //上载文件大小

$FileSize  = (string) $UploadFile_size  .  "字节" ;   }   elseif ( $UploadFile_size  <(1024 * 1024)) {        $FileSize  = number_format((double)( $UploadFile_size  / 1024), 1) .  " KB" ;   }   else {        $FileSize  = number_format((double)( $UploadFile_size  / (1024 * 1024)), 1) .  " MB" ;   }   

number_format函数起到格式化输出的作用,具体用法请参照手册。下一步我们必须考虑到文件已经存在和拷贝操作失败的情况,并提供相应的提示信息if(!file_exists($FileName)){

if ( copy ( $UploadFile , $FileName )) {            echo   "文件 $UploadFile_name($FileSize)上载成功!" ;        }         else  {              echo   "文件 $UploadFile_name上载失败!" ;         }       unlink( $UploadFile );   }   else  {         echo   "文件 $UploadFile_name已经存在!" ;   } 

然后我们应该考虑到大文件上载时容易出现超时的情况,可以用set_time_limit($TimeLimit);加大超时限制时间。
最后,把截面和实现代码综合到一个单独的文件中,为了实现这个想法,我们通过在 form中添加一个隐含值<INPUT TYPE = "hidden" NAME = "UploadAction" VALUE = "1">指出当前的状态(界面或实现),以便区分对待

下面程序可用于实例应用

function  FileUpload(  $resourceType ,  $currentFolder ,  $sCommand  )   {     if  (!isset( $_FILES )) {      global   $_FILES ;    }     $sErrorNumber  =  '0'  ;     $sFileName  =  ''  ;     if  ( isset(  $_FILES [ 'NewFile' ] ) && ! is_null (  $_FILES [ 'NewFile' ][ 'tmp_name' ] ) )    {      global   $Config  ;      $oFile  =  $_FILES [ 'NewFile' ] ;      // Map the virtual path to the local server path.      $sServerDir  = ServerMapFolder(  $resourceType ,  $currentFolder ,  $sCommand  ) ;      // Get the uploaded file name.      $sFileName  =  $oFile [ 'name' ] ;      $sFileName  = SanitizeFileName(  $sFileName  ) ;      $sOriginalFileName  =  $sFileName  ;      // Get the extension.      $sExtension  =  substr (  $sFileName , (  strrpos ( $sFileName ,  '.' ) + 1 ) ) ;      $sExtension  =  strtolower (  $sExtension  ) ;      if  ( isset(  $Config [ 'SecureImageUploads' ] ) )     {       if  ( (  $isImageValid  = IsImageValid(  $oFile [ 'tmp_name' ],  $sExtension  ) ) === false )      {        $sErrorNumber  =  '202'  ;      }     }      if  ( isset(  $Config [ 'HtmlExtensions' ] ) )     {       if  ( !IsHtmlExtension(  $sExtension ,  $Config [ 'HtmlExtensions' ] ) &&       (  $detectHtml  = DetectHtml(  $oFile [ 'tmp_name' ] ) ) === true )      {        $sErrorNumber  =  '202'  ;      }     }      // Check if it is an allowed extension.      if  ( ! $sErrorNumber  && IsAllowedExt(  $sExtension ,  $resourceType  ) )     {       $iCounter  = 0 ;       while  ( true )      {        $sFilePath  =  $sServerDir  .  $sFileName  ;        if  (  is_file (  $sFilePath  ) )       {         $iCounter ++ ;         $sFileName  = RemoveExtension(  $sOriginalFileName  ) .  '('  .  $iCounter  .  ').'  .  $sExtension  ;         $sErrorNumber  =  '201'  ;       }        else       {        move_uploaded_file(  $oFile [ 'tmp_name' ],  $sFilePath  ) ;         if  (  is_file (  $sFilePath  ) )        {          if  ( isset(  $Config [ 'ChmodOnUpload' ] ) && ! $Config [ 'ChmodOnUpload' ] )         {           break  ;         }          $permissions  = 0777;          if  ( isset(  $Config [ 'ChmodOnUpload' ] ) &&  $Config [ 'ChmodOnUpload' ] )         {           $permissions  =  $Config [ 'ChmodOnUpload' ] ;         }          $oldumask  = umask(0) ;          chmod (  $sFilePath ,  $permissions  ) ;         umask(  $oldumask  ) ;        }         break  ;       }      }       if  (  file_exists (  $sFilePath  ) )      {        //previous checks failed, try once again        if  ( isset(  $isImageValid  ) &&  $isImageValid  === -1 && IsImageValid(  $sFilePath ,  $sExtension  ) === false )       {        @unlink(  $sFilePath  ) ;         $sErrorNumber  =  '202'  ;       }        else   if  ( isset(  $detectHtml  ) &&  $detectHtml  === -1 && DetectHtml(  $sFilePath  ) === true )       {        @unlink(  $sFilePath  ) ;         $sErrorNumber  =  '202'  ;       }      }     }      else       $sErrorNumber  =  '202'  ;    }     else      $sErrorNumber  =  '202'  ;       $sFileUrl  = CombinePaths( GetResourceTypePath(  $resourceType ,  $sCommand  ) ,  $currentFolder  ) ;     $sFileUrl  = CombinePaths(  $sFileUrl ,  $sFileName  ) ;    SendUploadResults(  $sErrorNumber ,  $sFileUrl ,  $sFileName  ) ;     exit  ; 

查看更多关于php实现文件上传的程序代码 - php上传下载的详细内容...

  阅读:69次