php檔案讀寫操作

來源:互聯網
上載者:User

首先是一個檔案看能不能讀取(許可權問題),或者存在不,我們可以用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;
}
?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.