首先是一個檔案看能不能讀取(許可權問題),或者存在不,我們可以用is_readable函數擷取資訊.:
php/func_filesystem_is_readable.htm">is_readable函數用法
| 代碼如下 |
複製代碼 |
<?php $file = "test.txt"; if(is_readable($file)) { echo ("$file is readable"); } else { echo ("$file is not readable"); } ?> |
輸出:
test.txt is readable
利用file_get_contents函數來讀取檔案,這個函數可以讀取大資料量的檔案,也可以讀取遠程伺服器檔案,但必須在php.ini開始allow_url_fopen = On否則此函數不可用。
| 代碼如下 |
複製代碼 |
<?php $file = "filelist.php"; if (file_exists($file) == false) { die('檔案不存在'); } $data = file_get_contents($file); echo htmlentities($data); ?> |
讀取遠程 檔案,這是本教程這外的話題了。
| 代碼如下 |
複製代碼 |
function vita_get_url_content($url) { if(function_exists('file_get_contents')) { $file_contents = file_get_contents($url); } else { $ch = curl_init(); $timeout = 5; curl_setopt ($ch, curlopt_url, $url); curl_setopt ($ch, curlopt_returntransfer, 1); curl_setopt ($ch, curlopt_connecttimeout, $timeout); $file_contents = curl_exec($ch); curl_close($ch); } return $file_contents; } |
利用fread函數
來讀取檔案,這個函數可以讀取指定大小的資料量
//fread讀取檔案執行個體一
| 代碼如下 |
複製代碼 |
$filename = "/www.111cn.net/local/something.txt"; $handle = fopen($filename, "r"); $contents = fread($handle, filesize($filename)); fclose($handle); |
//php5以上版本讀取遠程伺服器內容
| 代碼如下 |
複製代碼 |
$handle = fopen("http://www.111cn.net/", "rb"); $contents = stream_get_contents($handle); fclose($handle); |
還有一種方式,可以讀取二進位的檔案:
| 代碼如下 |
複製代碼 |
$data = implode('', file($file)); |
fwrite 檔案的寫操作
fwrite() 把 string 的內容寫入檔案指標 file 處。 如果指定了 length,當寫入了 length 個位元組或者寫完了 string 以後,寫入就會停止,視乎先碰到哪種情況。
fwrite() 返回寫入的字元數,出現錯誤時則返回 false。
檔案寫入函式:
| 代碼如下 |
複製代碼 |
<?php //檔案寫入函式 function PHP_Write($file_name,$data,$method="w") { $filenum=@fopen($file_name,$method); flock($filenum,LOCK_EX); $file_data=fwrite($filenum,$data); fclose($filenum); return $file_data; } ?> |