PHP學習筆記(三)--檔案操作
下面通過一些簡單示例帶你瞭解PHP的檔案操作。
1、開啟及關閉檔案
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
mode |
說明 |
'r' |
只讀方式開啟,將檔案指標指向檔案頭。 |
'r+' |
讀寫方式開啟,將檔案指標指向檔案頭。 |
'w' |
寫入方式開啟,將檔案指標指向檔案頭並將檔案大小截為零。如果檔案不存在則嘗試建立之。 |
'w+' |
讀寫方式開啟,將檔案指標指向檔案頭並將檔案大小截為零。如果檔案不存在則嘗試建立之。 |
'a' |
追加方式開啟。寫入方式開啟,將檔案指標指向檔案末尾。如果檔案不存在則嘗試建立之。 |
'a+' |
追加方式開啟。讀寫方式開啟,將檔案指標指向檔案末尾。如果檔案不存在則嘗試建立之。 |
'x' |
建立並以寫入方式開啟,將檔案指標指向檔案頭。如果檔案已存在,則 fopen() |
'x+' |
建立並以讀寫方式開啟,其他的行為和 'x' 一樣。 |
b |
二進位制模式,用於與其它模式進行連線,預設方式是二進位制模式。 |
t |
文字檔案模式,用於與其它模式進行連線。 |
關閉開啟的檔案:bool fclose ( resource $handle )
<?php
$fileName='D:\tmp.txt';
$handle=fopen($fileName, "rb");
while(!feof($handle)){
echo fgets($handle);
}
fclose($handle);
?>
2、讀寫檔案
- 讀取整個檔案內容
reaffile()、file()和file_get_contents()用於讀取整個檔案內容。使用這三個函式讀取檔案內容不需要開啟關閉檔案。
- int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
readfile()讀取整個檔案的內容並寫入到快取中,出錯則返回fase。
- array file ( string $filename [, int $flags = 0 [, resource $context ]] )
file()函式讀取整個檔案的內容按行儲存到陣列中,包括換行符在內。
可選引數 flags 可以是以下一個或多個常量:
FILE_USE_INCLUDE_PATH
在 include_path 中查詢檔案。
FILE_IGNORE_NEW_LINES
在陣列每個元素的末尾不要新增換行符
FILE_SKIP_EMPTY_LINES
跳過空行
- string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
file_get_contents()將檔案內容讀入到一個字串,如果有offset及maxlen引數,則從引數offset指定的位置開始讀取長度為maxlen的一個字串,如果讀取失敗則返回false。
【例1】使用readfile()函式
<?php
$fileName='D:\tmp.txt';
readfile($fileName);//顯示所有內容
$a=readfile($fileName);//返回總字數並且顯示所有內容
echo $a;
?>
【例2】使用file()函式
<?php
$fileName='D:\tmp.txt';
if (file_exists($fileName))//判斷檔案是否存在
{
$arr=file($fileName);
foreach ($arr as $value){//每次輸出一個文字檔案的段落
echo $value.'<p>';
}
}
?>
【例3】使用file_get_contents()函式
<?php
$fileName='D:\tmp.txt';
$strContent=file_get_contents($fileName);
echo $strContent;
$strContent=file_get_contents($fileName,null,null,11,20);//從第11個字元開始讀取,讀取長度為20(一個漢字佔兩個字元)
echo $strContent;
?>
<?php
// <= PHP 5
$file = file_get_contents ( './people.txt' , true );
// > PHP 5
$file = file_get_contents ( './people.txt' , FILE_USE_INCLUDE_PATH );
?>
<?php
$homePage='http://www.baidu.com/';
$content=file_get_contents($homePage);
echo $content;
?>
- 讀取一行資料
- string fgets ( resource $handle [, int $length ] )
一次讀取一行資料,引數length為讀取長度,遇到換行符、EOF或讀取了length-1個字元後停止。
- string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )
用於讀取一行資料,會過濾掉讀取內容中的html和php標記,引數allowable_tags可以設定哪些標記不被去掉。
【例1】使用fgets()函式
<?php
$fileName='D:\tmp.txt';
if(file_exists($fileName)){
$handle=fopen($fileName, 'rb');
while(!feof($handle)){
echo fgets($handle).'<p>';
}
fclose($handle);
}
?>
【例2】使用fegtss()函式
<?php
$fileName='D:\tmp.txt';
if(file_exists($fileName)){
$handle=fopen($fileName, 'rb');
while(!feof($handle)){
echo fgetss($handle).'<p>';
}
fclose($handle);
}
?>
- 讀取一個字元
string fgetc ( resource $handle )
從檔案中讀取一個字元
<?php
$fileName='D:\tmp.txt';
if(file_exists($fileName)){
$handle=fopen($fileName, 'rb');
while(false!=($chr=fgetc($handle))){
echo $chr;
}
fclose($handle);
}
?>
注意:使用此方法對於中文來說讀取的是亂碼
- 讀取指定長度的字元
string fread ( resource $handle , int $length )
引數length為要讀取的位元組數。
<?php
$fileName='D:\tmp.txt';
if(file_exists($fileName)){
$handle=fopen($fileName, 'rb');
echo fread($handle, 32).'<p>';//讀取32個位元組
echo fread($handle, filesize($fileName));//讀取剩餘內容
fclose($handle);
}
?>
3、資料寫入檔案
- int fwrite ( resource $handle , string $string [, int $length ] )
fputs()與fwrite用法完全相同。
<?php
$fileName='D:\tmp.txt';
$content='要新增到檔案的內容';
if(is_writable($fileName)){//判斷檔案是否可寫
$handle=fopen($fileName, "a");
if(!$handle)
{
echo '開啟檔案失敗';
exit;
}
if ( fwrite ( $handle , $content ) === FALSE ) {
echo "不能寫入到檔案 $fileName " ;
}
echo '寫入成功';
fclose($handle);
}
else{
echo '不能寫入檔案';
}
?>
- int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
flags 的值可以是 以下 flag 使用 OR (|) 運算子進行的組合。
Available flags |
|
Flag |
描述 |
FILE_USE_INCLUDE_PATH |
在 include 目錄裡搜尋 filename。 更多資訊可參見 include_path。 |
FILE_APPEND |
如果檔案 filename 已經存在,追加資料而不是覆蓋。 |
LOCK_EX |
在寫入時獲得一個獨佔鎖。 |
<?php
$fileName='D:\tmp.txt';
$content='要新增到檔案的內容';
file_put_contents($fileName, $content,FILE_APPEND|LOCK_EX);//向檔案追加內容並且寫入時加鎖
?>
- bool copy ( string $source , string $dest [, resource $context ] )
拷貝檔案,如果目標檔案存在,則會被覆蓋
- bool rename ( string $oldname , string $newname [, resource $context ] )
檔案重新命名,可以跨驅動器進行操作。
- bool unlink ( string $filename [, resource $context ] )
刪除檔案
- int fileatime ( string $filename )
獲取檔案上次訪問時間,返回時間戳
- int filemtime ( string $filename )
返回最後一次修改時間,返回時間戳
- int filesize ( string $filename )
獲取檔案大小,單位為位元組數
- mixed pathinfo ( string $path [, int $options = PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME ] )
返回一個數組包含檔案name的路徑資訊。它們包括: PATHINFO_DIRNAME , PATHINFO_BASENAME 和 PATHINFO_EXTENSION 或 PATHINFO_FILENAME 。 如果沒有指定 options 預設是返回全部的單元。
- string realpath ( string $path )
返回檔案的絕對路徑
- array stat ( string $filename )
返回一個數組,包括檔案大小、最後修改時間等資訊。
<?php
$fileName='D:\tmp.txt';
copy($fileName, 'D:\123.txt');
rename($fileName, 'D:\12.txt');
unlink('D:\123.txt');
$lastTime=fileatime($fileName);//返回時間戳
echo '上次訪問時間:'.date('Y-m-d H:i:s',$lastTime).'<p>';
echo '上次修改時間:'.date('Y-m-d H:i:s',filemtime($fileName)).'<p>';
$size=filesize($fileName);
echo '檔案大小'.$size.'<p>';
$arr=pathinfo($fileName);
print_r($arr);
echo '<p>';
echo '檔案路徑:'.$arr['dirname'].'<p>';
echo '檔案全名:'.$arr['basename'].'<p>';//包括副檔名
echo '副檔名:'.$arr['extension'].'<p>';
echo '檔名:'.$arr['filename'].'<p>';//不包括副檔名
echo realpath("index.php");
$arrInfo=stat($fileName);
foreach ($arrInfo as $key=>$value){
echo $key.':'.$value.'<p>';
}
?>
4、目錄處理
- resource opendir ( string $path [, resource $context ] )
開啟一個目錄
- void closedir ( resource $dir_handle )
關閉開啟的目錄
- array scandir ( string $directory [, int $sorting_order [, resource $context ]] )
返回一個數組,包括所有檔案和目錄。
- bool mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] )
新建一個指定的目錄
- bool rmdir ( string $dirname [, resource $context ] )
刪除指定的目錄,目錄必須是空的
- string getcwd ( void )
返回當前目錄
- bool chdir ( string $directory )
將當前目錄改為directory
- float disk_free_space ( string $directory )
返回目錄中的可用空間
- float disk_total_space ( string $directory )
返回目錄的總空間大小
- string readdir ([ resource $dir_handle ] )
返回目錄中的下一個檔案的檔名,必須使用opendir()開啟目錄
- void rewinddir ( resource $dir_handle )
將指定的目錄重新指定到目錄的開頭
【例1】
<?php
$pathInfo=pathinfo(realpath("index.php"),PATHINFO_DIRNAME);
if (is_dir($pathInfo)){
if($dire=opendir($pathInfo)){
echo $dire;
}
closedir($dire);
}
$dir=scandir("E:\\臨時檔案");
foreach ($dir as $value){
echo $value.'<p>';
}
mkdir('D:\tmp');
rmdir('D:\tmp');
echo getcwd().'<p>';
echo '當前目錄總空間:'.disk_total_space(getcwd()).'<p>';
echo '空閒目錄大小:'.disk_free_space(getcwd());
?>
【例2】兩種方法遍歷目錄檔案
<?php
$handle=opendir(getcwd());
while(true==($value=readdir($handle))){
echo $value.'<p>';
}
$arr=scandir(getcwd());
foreach ($arr as $value){
echo $value.'<p>';
}
?>
5、檔案高階處理
- bool rewind ( resource $handle )
將檔案的指標設為檔案流的開頭。如果以追加方式開啟,則無論檔案指標在何處,總是會追加到檔案末尾。
- int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )
offset為指標位置或相對whence引數的偏移量,可以是負值。
whence引數可以取值如下:
1. SEEK_SET - 設定位置等於 offset 位元組。
2. SEEK_CUR - 設定位置為當前位置加上 offset。
3. SEEK_END - 設定位置為檔案尾加上 offset。
如果忽略whence引數,則預設為SEEK_SET.
- bool feof ( resource $handle )
測試是否到了檔案的結束的位置
- int ftell ( resource $handle )
返回檔案當前指標的位置
- bool flock ( resource $handle , int $operation [, int &$wouldblock ] )
在向一個檔案寫入內容時,需要先鎖定該檔案,以防止其它使用者同時修改此檔案內容。
operation 可以是以下值之一:
1. LOCK_SH 取得共享鎖定(讀取的程式)。
2. LOCK_EX 取得獨佔鎖定(寫入的程式。
3. LOCK_UN 釋放鎖定(無論共享或獨佔)。
如果不希望 flock() 在鎖定時堵塞,則是 LOCK_NB (Windows 上還不支援)。
6、上傳檔案
使用檔案上傳需要配置php.ini中的一些屬性:
- file_upload:設定為on才支援上傳檔案;
- upload_tmp_dir:上傳檔案臨時目錄;
- upload_max_filesize:伺服器上傳的檔案的最大值,以MB為單位,預設為20MB;
- max_execution_time:PHP中一個指令執行的最長時間;
- memory_limit:PHP中一個指令所分配的記憶體空間,單位為MB。
如果需要上傳超大檔案需要修改最後三個屬性。
$_FILES變數儲存的上傳檔案的相關資訊。
元素名 |
說明 |
$_FILES[filename][name] |
儲存了上傳檔案的檔名,如exam.txt、myDream.jpg等 |
$_FILES[filename][size] |
儲存了上傳檔案的大小,單位為位元組 |
$_FILES[filename][type_name] |
檔案上傳時,首先在臨時目錄中儲存一個臨時檔案。該變數為臨時檔案。 |
$_FILES[filename][type] |
上傳檔案的型別 |
$_FILES[filename][error] |
儲存了上傳檔案的結果。如果為0則說明上傳成功 |
bool move_uploaded_file ( string $filename , string $destination )
上傳檔案到指定位置。在建立表單時,必須設定form表單的enctype=”multipart/form-data”.
<?php
$uploads_dir = '/uploads' ;
foreach ( $_FILES [ "pictures" ][ "error" ] as $key => $error ) {
if ( $error == UPLOAD_ERR_OK ) {
$tmp_name = $_FILES [ "pictures" ][ "tmp_name" ][ $key ];
$name = $_FILES [ "pictures" ][ "name" ][ $key ];
move_uploaded_file ( $tmp_name , " $uploads_dir / $name " );
}
}
?>