以下是個人總結的PHP檔案操作函數。當然,這隻是部分,還有很多,我沒有列出來。
一 、解析路徑:
1 獲得檔案名稱:
basename();
給出一個包含有指向一個檔案的全路徑的字串,本函數返回基本的檔案名稱。如果檔案名稱是以 suffix 結束的,那這一部分也會被去掉。
eg:
複製代碼 代碼如下:$path = "/home/httpd/html/index.php";
$file = basename($path,".php"); // $file is set to "index"
2 得到目錄部分:
dirname();
給出一個包含有指向一個檔案的全路徑的字串,本函數返回去掉檔案名稱後的目錄名。
eg: 複製代碼 代碼如下:$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"
3 得到路徑關聯陣列
pathinfo();
得到一個指定路徑中的三個部分:目錄名,基本名,副檔名。
eg: 複製代碼 代碼如下:$pathinfo = pathinfo("www/test/index.html");
var_dump($pathinfo);
// $path['dirname']
$path['basename']
$path['extenssion']
二、檔案類型
1. filetype();
返迴文件的類型。可能的值有 fifo,char,dir,block,link,file 和 unknown。
eg: 複製代碼 代碼如下:echo filetype('/etc/passwd'); // file
echo filetype('/etc/'); // dir
三、得到給定檔案有用資訊數組(很有用)
1. fstat();
通過已開啟的檔案指標取得檔案資訊
擷取由檔案指標 handle 所開啟檔案的統計資訊。本函數和 stat() 函數相似,除了它是作用於已開啟的檔案指標而不是檔案名稱。
eg: 複製代碼 代碼如下:// 開啟檔案
$fp = fopen("/etc/passwd", "r");
// 取得統計資訊
$fstat = fstat($fp);
// 關閉檔案
fclose($fp);
// 只顯示關聯陣列部分
print_r(array_slice($fstat, 13));
2. stat()
擷取由 filename 指定的檔案的統計資訊(類比fstat())
四、計算大小
1. filesize()
返迴文件大小的位元組數,如果出錯返回 FALSE 並產生一條 E_WARNING 級的錯誤。
eg: 複製代碼 代碼如下:// 輸出類似:somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
2. disk_free_space()
獲得目錄所在磁碟分割的可用空間(位元組單位)
eg
[code]
// $df 包含根目錄下可用的位元組數
$df = disk_free_space("/");
//在 Windows 下:
disk_free_space("C:");
disk_free_space("D:");
3. disk_total_space()
返回一個目錄的磁碟總大小
eg:(同上,換掉函數)
另:如需要計算一個目錄大小,可以編寫一個遞迴函式來實現
代碼 複製代碼 代碼如下:function dir_size($dir){
$dir_size = 0;
if($dh = @opendir($dir)){
while(($filename = readdir($dh)) != false){
if($filename !='.' and $filename !='..'){
if(is_file($dir.'/'.$filename)){
$dir_size +=filesize($dir.'/'.$filename);
}else if(is_dir($dir.'/'.$filename)){
$dir_size +=dir_size($dir.'/'.$filename);
}
}
}#end while
}# end opendir
@closedir($dh);
return $dir_size;
} #end function
五、訪問與修改時間
1. fileatime(): 最後訪問時間
2. filectime(): 最後改變時間(任何資料的修改)
3. filemtime(): 最後修改時間(指僅是內容修改)
六、 檔案的I/O操作
1. fopen -- 開啟檔案或者 URL
mode 說明
'r' 唯讀方式開啟,將檔案指標指向檔案頭。
'r+' 讀寫方式開啟,將檔案指標指向檔案頭。
'w' 寫入方式開啟,將檔案指標指向檔案頭並將檔案大小截為零。如果檔案不存在則嘗試建立之。
'w+' 讀寫方式開啟,將檔案指標指向檔案頭並將檔案大小截為零。如果檔案不存在則嘗試建立之。
'a' 寫入方式開啟,將檔案指標指向檔案末尾。如果檔案不存在則嘗試建立之。
'a+' 讀寫方式開啟,將檔案指標指向檔案末尾。如果檔案不存在則嘗試建立之。
'x' 建立並以寫入方式開啟,將檔案指標指向檔案頭。如果檔案已存在,則 fopen() 調用失敗並返回 FALSE,
'x+' 建立並以讀寫方式開啟,將檔案指標指向檔案頭。如果檔案已存在,則 fopen() 調用失敗並返回 FALSE
eg: 複製代碼 代碼如下:$handle = fopen("/home/rasmus/file.txt", "r");
2. file -- 把整個檔案讀入一個數組中(此函數是很有用的)
和 file_get_contents() 一樣,只除了 file() 將檔案作為一個數組返回。數組中的每個單元都是檔案中相應的一行,包括分行符號在內。如果失敗 file() 返回 FALSE。
eg:
代碼 複製代碼 代碼如下:$lines = file('http://www.example.com/');
// 在數組中迴圈,顯示 HTML 的源檔案並加上行號。
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 另一個例子將 web 頁面讀入字串。參見 file_get_contents()。
$html = implode('', file ('http://www.example.com/'));
3. fgets -- 從檔案指標中讀取一行
從 handle 指向的檔案中讀取一行並返回長度最多為 length - 1 位元組的字串。碰到分行符號(包括在傳回值中)、EOF 或者已經讀取了 length - 1 位元組後停止(看先碰到那一種情況)。如果沒有指定 length,則預設為 1K,或者說 1024 位元組。
eg: 複製代碼 代碼如下:$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
echo $buffer;
}
fclose($handle);
}
4. fgetss -- 從檔案指標中讀取一行並過濾掉 HTML 標籤
和 fgets() 相同,只除了 fgetss 嘗試從讀取的文本中去掉任何 HTML 和 PHP 標記。
可以用可選的第三個參數指定哪些標記不被去掉
另:對的目錄的操作:
1. opendir -- 開啟目錄控制代碼,開啟一個目錄控制代碼,可用於之後的 closedir(),readdir() 和 rewinddir() 調用中。
2. readdir -- 從目錄控制代碼中讀取條目,返回目錄中下一個檔案的檔案名稱。檔案名稱以在檔案系統中的排序返回。
eg:
代碼 複製代碼 代碼如下:// 注意在 4.0.0-RC2 之前不存在 !== 運算子
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Files:\n";
while (false !== ($file = readdir($handle))) {
echo "$file\n";
}
while ($file = readdir($handle)) {
echo "$file\n";
}
closedir($handle);
}
[code]
3. scandir -- 列出指定路徑中的檔案和目錄(很有用),返回一個 array,包含有 directory 中的檔案和目錄。
預設的排序次序是按字母升序排列。如果使用了選擇性參數 sorting_order(設為 1),則排序次序是按字母降序排列。
eg:
[code]
$dir = '/tmp';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
print_r($files1);
print_r($files2);
另外註:
七、對檔案屬性的操作(作業系統環境不同,可能有所不一樣,這點要注意)
1檔案是否可讀:
boolis_readable ( string filename )
如果由 filename 指定的檔案或目錄存在並且可讀則返回 TRUE。
記住 PHP 也許只能以運行 webserver 的使用者名稱(通常為 'nobody')來訪問檔案。不計入安全模式的限制。
2 檔案是否可寫
bool is_writable ( string filename )
如果檔案存在並且可寫則返回 TRUE。filename 參數可以是一個允許進行是否可寫檢查的目錄名。
記住 PHP 也許只能以運行 webserver 的使用者名稱(通常為 'nobody')來訪問檔案。不計入安全模式的限制
3 檢查檔案是否存在
boolfile_exists ( string filename )
如果由 filename 指定的檔案或目錄存在則返回 TRUE,否則返回 FALSE
=====================================PHP檔案操作類========================================= 複製代碼 代碼如下:<?php
/***************************************************************************************
檔案名稱:File.cls.php
檔案簡介:類clsFile的定義,對檔案操作的封裝
版本:2.0 最後修改日期:2011-8-23
****************************************************************************************/
!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;
}
/******************備份檔案夾*********************/
}
?>
希望對你有用.