PHP目錄文件操作函數目錄操作詳談

目錄,文件操作詳談—php

 

● 寫文件

和讀取文件的方式一樣,先看看是不是能寫:

<?php

$file = 'dirlist.php';
if (is_writable($file) == false) {
        die("我是雞毛,我不能");
}
?>

能寫了的話可以使用file_put_contents函數寫入:

<?php
$file = 'dirlist.php';
if (is_writable($file) == false) {
        die('我是雞毛,我不能');
}
$data = '我是可鄙,我想要';
file_put_contents ($file, $data);
?>

file_put_contents函數在php5中新引進的函數(不知道存在的話用function_exists函數先判斷一下)低版本的php無法使用,可以使用如下方式:

$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);

替換之.

寫文件的時候有時候需要鎖定,然後寫:

function cache_page($pageurl,$pagedata){
 if(!$fso=fopen($pageurl,'w')){
  $this->warns('無法打開緩存文件.');//trigger_error
  return false;
 }
 if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型鎖定
  $this->warns('無法鎖定緩存文件.');//trigger_error
  return false;
 }
 if(!fwrite($fso,$pagedata)){//寫入字節流,serialize寫入其他格式
  $this->warns('無法寫入緩存文件.');//trigger_error
  return false;
 }
 flock($fso,LOCK_UN);//釋放鎖定
 fclose($fso);
 return true;
}

● 複製,刪除文件

php刪除文件非常easy,用unlink函數簡單操作:

<?php
$file = 'dirlist.php';
$result = @unlink ($file);
if ($result == false) {
        echo '蚊子趕走了';
} else {
        echo '無法趕走';
}
?>

即可.

複製文件也很容易:

<?php
$file = 'yang.txt';
$newfile = 'ji.txt'; # 這個文件父文件夾必須能寫
if (file_exists($file) == false) {
        die ('小樣沒上線,無法複製');
}
$result = copy($file, $newfile);
if ($result == true) {
        echo '複製記憶ok';
}
?>

可以使用rename()函數重命名一個文件夾.其他操作都是這幾個函數組合一下就能實現的.

● 獲取文件屬性

我說幾個常見的函數:
獲取最近修改時間:

<?php
$file = 'test.txt';
echo date('r', filemtime($file));
?>

返回的說unix的時間戳,這在緩存技術常用.

相關的還有獲取上次被訪問的時間fileatime(),filectime()當文件的權限,所有者,所有組或其它 inode 中的元數據被更新時間,fileowner()函數返回文件所有者

$owner = posix_getpwuid(fileowner($file));

(非window系統),ileperms()獲取文件的權限,

<?php
$file = 'dirlist.php';
$perms = substr(sprintf('%o', fileperms($file)), -4);
echo $perms;
?>

filesize()返回文件大小的字節數:

<?php

// 輸出類似:somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

?>

獲取文件的全部信息有個返回數組的函數stat()函數:

<?php
$file = 'dirlist.php';
$perms = stat($file);
 var_dump($perms);
?>

那個鍵對應什麼可以查閱詳細資料,此處不再展開.

 
發佈了43 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章