PHP文件操作類(含獲取文件內容及屬性,更改文件,文件超出一定大小時刪除)
<?php class fileinfo { public $file; function __construct($f) { $this->file = $f; } function createfile() { touch($this->file) or die("Couldn't create $this->file,sorry!"); } function modifilefile() { $fo = fopen($file,"w") or die("Couldn't open $this->file,sorry!"); if($fo) { fwrite($fo,"It's just a test by Adam Li on ".date("D d M Y H:i:s",time())) or die("$this->file isn't writable,sorry!"); fclose($fo); } } function getfileinfo() { if(file_exists($this->file)) { //文件大于1024字節時刪除并重新創建空文件: if(filesize($this->file)>1024) { echo "<script>alert('File is more than 1024 bytes and will be deleted soon···')</script>"; if(unlink($this->file)) { echo "<script>alert('File has been deleted and system will create a same file but empty soon···')</script>"; touch($this->file) or die("Couldn't create ".$this->file); } } //獲取文件里的內容,避免再寫入時被覆蓋: $con = file_get_contents($this->file); $fo = fopen($this->file,"w") or die("Couldn't open $this->file,sorry!"); if($fo) { //連同文件之前的內容一起寫入: fwrite($fo,$con."<br>It's just a test by Adam Li on ".date("D d M Y H:i:s",time())) or die("$file isn't writable,sorry!"); fclose($fo); } } else//如果文件不存在,直接創建,寫入內容: { $this->createfile(); $this->modifilefile(); } //以下是獲取文件屬性: //獲取文件大小: echo "<p>文件".$this->file."大小為:<font color=red>".filesize($this->file)." bytes;</font></p>"; //檢查是否是文件: echo "<p>$this->file is ".(is_file($this->file)?"":"not ")."a file</p>"; //檢查是否是目錄: echo "<p>$this->file is ".(is_dir($this->file)?"":"not ")."a directory</p>"; //檢查文件是否可讀: echo "<p>$this->file is ".(is_readable($this->file)?"":"not ")."readable</p>"; //檢查文件是否可寫: echo "<p>$this->file is ".(is_writable($this->file)?"":"not ")."writable</p>"; //檢查文件是否可執行: echo "<p>$this->file is ".(is_executable($this->file)?"":"not ")."executable</p>"; //取得文件的上次訪問時間 echo "<p>$this->file was accessed on ".date("D d M Y H:i:s",fileatime($this->file))."</p>"; //取得文件修改時間 echo "<p>$this->file was modified on ".date("D d M Y H:i:s",filemtime($this->file))."</p>"; //取得文件的 inode 修改時間 echo "<p>$this->file was changed on ".date("D d M Y H:i:s",filectime($this->file))."</p>"; //顯示此時文件里的所有內容: echo "<p>文件里的內容是:<font color=red>".file_get_contents($this->file)."</font></p>"; } } $obj = new fileinfo("adam.txt"); $obj->getfileinfo(); ?>
本文由用戶 webphp 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!