PHP常用的文件操作函數

PHP常用的文件操作函數  


一 、解析路徑:


1 獲得文件名:basename();

2 得到目錄部分:dirname();

3 得到路徑關聯數組:pathinfo();

二、文件類型:

1. filetype();


三、得到給定文件有用信息數組(很有用)

1. fstat();通過已打開的文件指針取得文件信息

2. stat()獲取由 filename 指定的文件的統計信息(類比fstat())


四、計算大小

1. filesize()

2. disk_free_space()獲得目錄所在磁盤分區的可用空間(字節單位)

3. disk_total_space()返回一個目錄的磁盤總大小


五、 訪問與修改時間

1. fileatime(): 最後訪問時間

2. filectime(): 最後改變時間(任何數據的修改)

3. filemtime(): 最後修改時間(指僅是內容修改)


六、 文件的I/O操作

1. fopen -- 打開文件或者 URL

2. file -- 把整個文件讀入一個數組中(此函數是很有用的)

3. fgets -- 從文件指針中讀取一行

4. fgetss -- 從文件指針中讀取一行並過濾掉 HTML 標記(和 fgets() 相同,只除了 fgetss 嘗試從讀取的文本中去掉任何 HTML 和 PHP 標記)。


七、對目錄的操作:

1. opendir -- 打開目錄句柄,打開一個目錄句柄,可用於之後的 closedir(),readdir() 和 rewinddir() 調用中。

2. readdir -- 從目錄句柄中讀取條目,返回目錄中下一個文件的文件名。文件名以在文件系統中的排序返回。

3. scandir -- 列出指定路徑中的文件和目錄(很有用),返回一個 array,包含有 directory 中的文件和目錄。


八、 對文件屬性的操作(操作系統環境不同,可能有所不一樣,這點要注意)


1、文件是否可讀:boolis_readable ( string filename )

2、文件是否可寫:bool is_writable ( string filename )

3、檢查文件是否存在 boolfile_exists ( string filename )


九、可直接使用在項目中的超強PHP文件操作類,



<?php  

/***************************************************************************************
文件名:File.cls.php
文件簡介:類clsFile的定義,對文件操作的封裝
****************************************************************************************/  
!defined('INIT_PHPV') && die('No direct script access allowed');  
class clsFile  
{  
   private $fileName_str;         //文件的路徑  
   private $fileOpenMethod_str;   //文件打開模式  
     
   function __construct($fileName_str='',$fileOpenMethod_str='readOnly')//路徑,默認爲空;模式,默認均爲只讀  
   {  
       //構造函數,完成數據成員的初始化  
       $this->fileName_str=$fileName_str;  
       $this->fileOpenMethod_str=$fileOpenMethod_str;  
   }  
     
   function __destruct()  
   {  
       //析構函數  
   }  
     
   public function __get($valName_val)//欲取得的數據成員名稱  
   {  
       //特殊函數,取得指定名稱數據成員的值  
          return $this->$valName_val;  
   }  
     
   private function on_error($errMsg_str='Unkown Error!',$errNo_int=0)//錯誤信息,錯誤代碼  
   {  
        echo '程序錯誤:'.$errMsg_str.'錯誤代碼:'.$errNo_int;//出錯處理函數  
   }  
     
   public function open()  
   {  
       //打開相應文件,返回文件資源標識  
          //根據fileOpenMethod_str選擇打開方式  
          switch($this->fileOpenMethod_str)  
          {  
                 case 'readOnly':  
                    $openMethod_str='r';      //只讀,指針指向文件頭  
                    break;  
                 case 'readWrite':  
                    $openMethod_str='r+';     //讀寫,指針指向文件頭  
                    break;  
                 case 'writeAndInit':  
                    $openMethod_str='w';      //只寫,指針指向文件頭將大小截爲零,不存在則創建  
                    break;  
                 case 'readWriteAndInit':  
                    $openMethod_str='r+';     //讀寫,指針指向文件頭將大小截爲零,不存在則創建  
                    break;  
                 case 'writeAndAdd':  
                    $openMethod_str='a';      //只寫,指針指向文件末尾,不存在則創建  
                    break;  
                 case 'readWriteAndAdd':  
                    $openMethod_str='a+';     //讀寫,指針指向文件末尾,不存在則創建  
                    break;  
                 default:  
                    $this->on_error('Open method error!',310);//出錯處理  
                    exit;  
          }  
            
          //打開文件         
          if(!$fp_res=fopen($this->fileName_str,$openMethod_str))  
          {  
                 $this->on_error('Can\'t open the file!',301);//出錯處理  
                 exit;  
          }  
            
          return $fp_res;  
   }  
     
   public function close($fp_res)//由open返回的資源標識  
   {  
       //關閉所打開的文件  
          if(!fclose($fp_res))  
          {  
                 $this->on_error('Can\'t close the file!',302);//出錯處理  
                 exit;  
          }  
   }  
     
   public function write()//$fp_res,$data_str,$length_int:文件資源標識,寫入的字符串,長度控制  
   {  
       //將字符串string_str寫入文件fp_res,可控制寫入的長度length_int  
          //判斷參數數量,調用相關函數  
          $argNum_int=func_num_args();//參數個數  
            
          $fp_res=func_get_arg(0);          //文件資源標識  
          $data_str=func_get_arg(1);        //寫入的字符串  
            
          if($argNum_int==3)  
          {  
                 $length_int=func_get_arg(2);  //長度控制  
              if(!fwrite($fp_res,$data_str,$length_int))  
              {  
                    $this->on_error('Can\'t write the file!',303);//出錯處理  
                    exit;  
              }  
          }  
          else  
          {  
                 if(!fwrite($fp_res,$data_str))  
              {  
                    $this->on_error('Can\'t write the file!',303);//出錯處理  
                    exit;  
              }  
          }  
   }  
     
   public function read_line()//$fp_res,$length_int:文件資源標識,讀入長度  
   {  
       //從文件fp_res中讀入一行字符串,可控制長度  
          //判斷參數數量  
          $argNum_int=func_num_args();  
          $fp_res=func_get_arg(0);  
            
          if($argNum_int==2)  
          {  
              $length_int=func_get_arg(1);  
              if($string_str=!fgets($fp_res,$length_int))  
              {  
                    $this->on_error('Can\'t read the file!',304);//出錯處理  
                    exit;  
              }  
              return $string_str;  
       }  
       else  
       {  
              if(!$string_str=fgets($fp_res))  
              {  
                    $this->on_error('Can\'t read the file!',304);//出錯處理  
                    exit;  
              }  
              return $string_str;  
          }  
   }  
     
   public function read($fp_res,$length_int)//文件資源標識,長度控制  
   {  
       //讀入文件fp_res,最長爲length_int  
          if(!$string_str=fread($fp_res,$length_int))  
          {  
                 $this->on_error('Can\'t read the file!',305);//出錯處理  
                 exit;  
          }  
          return $string_str;  
   }  
     
   public function is_exists($fileName_str)//文件名  
   {  
       //檢查文件$fileName_str是否存在,存在則返回true,不存在返回false  
          return file_exists($fileName_str);  
   }  
 
/******************取得文件大小*********************/  
/*
取得文件fileName_str的大小
$fileName_str 是文件的路徑和名稱
返回文件大小的值
*/  
   public function get_file_size($fileName_str)//文件名  
   {  
       return filesize($fileName_str);  
   }  
 
/******************轉換文件大小的表示方法*********************/  
/*
$fileSize_int文件的大小,單位是字節
返回轉換後帶計量單位的文件大小
*/  
   public function change_size_express($fileSize_int)//文件名  
   {  
       if($fileSize_int>1024)  
       {  
          $fileSizeNew_int=$fileSize_int/1024;//轉換爲K  
          $unit_str='KB';  
            if($fileSizeNew_int>1024)  
             {  
              $fileSizeNew_int=$fileSizeNew_int/1024;//轉換爲M  
              $unit_str='MB';  
             }  
          $fileSizeNew_arr=explode('.',$fileSizeNew_int);  
          $fileSizeNew_str=$fileSizeNew_arr[0].'.'.substr($fileSizeNew_arr[1],0,2).$unit_str;  
       }  
       return $fileSizeNew_str;  
   }  
/******************重命名文件*********************/  
/*
將oldname_str指定的文件重命名爲newname_str
$oldName_str是文件的原名稱
$newName_str是文件的新名稱
返回錯誤信息
*/   
   public function rename_file($oldName_str,$newName_str)  
   {  
          if(!rename($oldName_str,$newName_str))  
          {  
                 $this->on_error('Can\'t rename file!',308);  
                 exit;  
          }  
   }  
 
/******************刪除文件*********************/  
/*
將filename_str指定的文件刪除
$fileName_str要刪除文件的路徑和名稱
返回錯誤信息
*/  
   public function delete_file($fileName_str)//  
   {  
          if(!unlink($fileName_str))  
          {  
                 $this->on_error('Can\'t delete file!',309);//出錯處理  
                 exit;  
          }  
   }  
 
/******************取文件的擴展名*********************/  
/*
取filename_str指定的文件的擴展名
$fileName_str要取類型的文件路徑和名稱
返回文件的擴展名
*/  
   public function get_file_type($fileName_str)  
   {  
          $fileNamePart_arr=explode('.',$fileName_str);  
          while(list(,$fileType_str)=each($fileNamePart_arr))  
          {  
           $type_str=$fileType_str;  
          }  
           return $type_str;  
   }  
 
/******************判斷文件是否是規定的文件類型*********************/  
/*
$fileType_str規定的文件類型
$fileName_str要取類型的文件路徑和名稱
返回false或true
*/  
   public function is_the_type($fileName_str,$fileType_arr)  
   {  
       $cheakFileType_str=$this->get_file_type($fileName_str);  
       if(!in_array($cheakFileType_str,$fileType_arr))  
       {  
        return false;  
          }  
       else  
       {  
          return true;  
       }  
   }  
 
/******************上傳文件,並返回上傳後的文件信息*********************/  
/*
$fileName_str本地文件名
$filePath上傳文件的路徑,如果$filePath是str則上傳到同一目錄用一個文件命名,新文件名在其加-1,2,3..,如果是arr則順序命名
$allowType_arr允許上傳的文件類型,留空不限制
$maxSize_int允許文件的最大值,留空不限制
返回的是新文件信息的二維數組:$reFileInfo_arr
*/  
   public function upload_file($fileName_str,$filePath,$allowType_arr='',$maxSize_int='')  
{        
       $fileName_arr=$_FILES[$fileName_str]['name'];  //文件的名稱  
       $fileTempName_arr=$_FILES[$fileName_str]['tmp_name'];  //文件的緩存文件  
       $fileSize_arr=$_FILES[$fileName_str]['size'];//取得文件大小  
       $reFileInfo_arr=array();  
       $num=count($fileName_arr)-1;  
       for($i=0;$i<=$num;$i++)  
      {  
           if($fileName_arr[$i]!='')   
        {  
          if($allowType_arr!='' and !$this->is_the_type($fileName_arr[$i],$allowType_arr))//判斷是否是允許的文件類型  
          {  
           $this->on_error('The file is not allowed type!',310);//出錯處理  
           break;  
          }  
 
          if($maxSize_int!='' and $fileSize_arr[$i]>$maxSize_int)  
          {  
           $this->on_error('The file is too big!',311);//出錯處理  
           break;  
          }  
    
          $j=$i+1;  
          $fileType_str=$this->get_file_type($fileName_arr[$i]);//取得文件類型  
          if(!is_array($filePath))  
          {  
          $fileNewName_str=$filePath.'-'.($j).'.'.$fileType_str;  
          }  
          else  
          {  
          $fileNewName_str=$filePath_arr[$i].'.'.$fileType_str;  
          }  
          copy($fileTempName_arr[$i],$fileNewName_str);//上傳文件  
          unlink($fileTempName_arr[$i]);//刪除緩存文件  
 
          //---------------存儲文件信息--------------------//  
          $doFile_arr=explode('/',$fileNewName_str);  
          $doFile_num_int=count($doFile_arr)-1;  
          $reFileInfo_arr[$j]['name']=$doFile_arr[$doFile_num_int];  
          $reFileInfo_arr[$j]['type']=$fileType_str;  
          $reFileInfo_arr[$j]['size']=$this->change_size_express($fileSize_arr[$i]);  
      }  
   }  
   return $reFileInfo_arr;  
}  
 
/******************備份文件夾*********************/  
}  
 
?> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章