PHP 檔案管理

Posted: 2014 年 03 月 12 日 in php

檔案處理

  PHP也可進行一般檔案的處理,例如文字檔的開啟、讀取、寫人、關閉等等,甚至還可以進行檔案的複製、搬移、刪除,以及目錄的處理功能,唯在處理這些檔案之前,如果要透過Web的方式來處理,得先注意檔案在系統中的權限問題,像是Linux系統,一般檔案的權限可分為擁有者、群組、其他等三種不同的使用者權限,同時又區分「讀、寫、執行」三種屬性權限,所以,在使用時得先留意在那個系統(Linux或Windows)執行,以及上述權限問題等,才能順利操作PHP管理檔案。 以下就以一個文字檔為例,進行所謂的:

  • 開啟檔案 ─ fopen( )函數
  • 顯示檔案 ─ fpassthru ( )函數
  • 檔案內容讀取 ─ fread( ) 、fgets( )函數
  • 寫入檔案 ─ fwrite( ) 、fputs( ) 函數
  • 關閉檔案 ─ fclose ( ) 函數
  • 複製檔案 ─ copy ( ) 函數
  • 刪除檔案 ─ unlink( ) 函數

在操作這些檔案處理函數時,php.ini中的設定會影響這些函式的動作:

參數名稱
預設值
說明
參數可變更性
allow_url_fopen
1
是否允許利用網頁方式開啟檔案
php.ini
user_agent
設定PHP傳送時使用者代理
php.ini
default_socket_timeout
60秒
在使用連線功能時的逾時時間設定(即自動斷線時間)
php.ini
auto_detect_line_endings
Off
自動檢查「行」的結束(換行)
php.ini

 

fopen 開啟檔案
語法
fopen ( string filename, string mode [, int use_include_path [, resource zcontext]])

fopen ( string 檔案名稱, string 開啟模式 [, int use_include_path [, resource zcontext]])

說明
  1. filename可以是檔案名稱或絕對路徑的檔案
  2. 開啟模式如下表說明:

    開啟
    模式

    說明
    'r'
    開啟成唯讀檔
    'r+'
    開啟成可讀寫的檔案
    'w'
    開啟只有寫入的檔案,並將檔案長度設為零;如果檔案不存在,則建立。
    'w+'
    開啟可讀寫,如果檔案存在,則會清除所有內容,長度為零; 如果檔案不存在,則建立。
    'a'
    開啟只有寫入的檔案,資料由檔案尾部加入;如果檔案不存在,則建立。
    'a+'
    開啟可讀寫的檔案,資料由檔案尾部加入;如果檔案不存在,則建立。
    'x'
    建立並開啟只有寫入的檔案,資料由檔案開頭寫入;如果檔案存在,fopen( )函數將回應「false」,並發生錯誤;如果檔案不存在,則建立。這個參數自PHP 4.3.2 以後版本開始支援。.
    'x+'
    建立並開啟可讀寫的檔案,資料由檔案開頭寫入;如果檔案存在,fopen( )函數將回應「false」,並發生錯誤;如果檔案不存在,則建立。這個參數自PHP 4.3.2 以後版本開始支援。.
  3. include_path 是指定檔案可搜尋的路徑位置。
  4. 如果操作成功的話,會回傳一個「handle」值,失敗則傳回「 false 」

 

傳回值
resource
範例
01:
02:
03:
04:
05:
<?php
  if ( !($fp = fopen("file_ex.txt", "r")) ) {
    echo "無法開啟檔案";
  } 
?>
第02行:開啟檔案,「!」表示相反的意思;如果成功,則結果會回傳給$fp。

 

 
fpassthru 顯示檔案
語法
fpassthru ( resource handle)
說明
當fopen( )函數開啟檔案成功的話,使用fpassthru( )函數,會檔案內容全部輸出到網頁上。
傳回值
int
範例
01:
02:
03:
04:
05:
06:
07:
<?php
  if ( !($fp = fopen("file_ex.txt", "r")) ) {
    echo "無法開啟檔案";
  } else {
    fpassthru ($fp) ;
  }  
?>

ch8-1-2.php

執行程式

第02行:開啟檔案,「!」表示相反的意思;如果成功,則結果會回傳給$fp。

 

fread 讀取檔案
語法
fread ( resource handle, int length)
說明
  1. 由開啟的檔案中讀取一定長度的字串。
  2. 可配合 while 將整個檔案讀取出來。
傳回值
string
範例
01:
02:
03:
04:
05:
06:
07:
<?php
  if ( !($fp = fopen("file_ex.txt", "r")) ) {
    echo "無法開啟檔案";
  } else {
    while ( $buffer = fread($fp, 40) ) {
       echo "$buffer <BR>";
    }
  }  
?>

ch8-1-3.php

執行程式

第05行:每次讀取40個字元,一直到讀取完畢為止。
fwrite 寫入檔案
語法
fwrite ( resource handle, string string [, int length])
說明
將指定的字串寫入檔案中,如果有長度設定,則表示要寫入字串的字元數。
傳回值
int
範例
01:
02:
03:
04:
05:
06:
07:
08:

09:
<?php
  $add_str = "台中市教育資訊網路心";
  if ( !($fp = fopen("file_ex.txt", "a")) ) {
    echo "無法開啟檔案";
  } else {
      fwrite ($fp, $add_str); 
      fpassthru ($fp);
  }  
?>

ch8-1-4.php

執行程式

第03行:開啟檔案為可讀寫模式
第06行:寫入預設字串
第07行:顯示結果
fclose 關閉檔案
語法
fclose ( resource handle)
說明
關閉開啟的檔案;
傳回值
bool
copy 複製檔案
語法
copy ( string source, string dest)
說明
複製檔案,成功回傳TRUE失敗回傳FALSE;須注意檔案或目錄的權限
傳回值
bool
範例
01:
02:
03:
04:
05:
<?php
  if ( !copy("file_ex.txt", "file_ex.bak")) ) {
    echo "無法複製檔案";
  }  
?>
unlink 刪除檔案
語法
unlink ( string filename)
說明
刪除檔案,成功回傳TRUE失敗回傳FALSE;須注意檔案或目錄的權限
傳回值
bool
範例
01:
02:
03:
04:
05:
<?php
  if ( !unlink("file_ex.txt")) ) {
    echo "無法複製檔案";
  }  
?>
PHP處理檔案函數 (目前共有75個)
函數名稱
功能簡介
basename Returns filename component of path
chgrp Changes file group
chmod Changes file mode
chown Changes file owner
clearstatcache Clears file status cache
copy Copies file
delete See unlink() or unset()
dirname Returns directory name component of path
disk_free_space Returns available space in directory
disk_total_space Returns the total size of a directory
diskfreespace Alias of disk_free_space()
fclose Closes an open file pointer
feof Tests for end-of-file on a file pointer
fflush Flushes the output to a file
fgetc Gets character from file pointer
fgetcsv Gets line from file pointer and parse for CSV fields
fgets Gets line from file pointer
fgetss Gets line from file pointer and strip HTML tags
file_exists Checks whether a file or directory exists
file_get_contents Reads entire file into a string
file_put_contents Write a string to a file
file Reads entire file into an array
fileatime Gets last access time of file
filectime Gets inode change time of file
filegroup Gets file group
fileinode Gets file inode
filemtime Gets file modification time
fileowner Gets file owner
fileperms Gets file permissions
filesize Gets file size
filetype Gets file type
flock Portable advisory file locking
fnmatch Match filename against a pattern
fopen Opens file or URL
fpassthru Output all remaining data on a file pointer
fputs Alias of fwrite()
fread Binary safe file read
fscanf Parses input from a file according to a format
fseek Seeks on a file pointer
fstat Gets information about a file using an open file pointer
ftell Tells file pointer read/write position
ftruncate Truncates a file to a given length
fwrite Binary safe file write
glob Find pathnames matching a pattern
is_dir Tells whether the filename is a directory
is_executable Tells whether the filename is executable
is_file Tells whether the filename is a regular file
is_link Tells whether the filename is a symbolic link
is_readable Tells whether the filename is readable
is_uploaded_file Tells whether the file was uploaded via HTTP POST
is_writable Tells whether the filename is writable
is_writeable Alias of is_writable()
link Create a hard link
linkinfo Gets information about a link
lstat Gives information about a file or symbolic link
mkdir Makes directory
move_uploaded_file Moves an uploaded file to a new location
parse_ini_file Parse a configuration file
pathinfo Returns information about a file path
pclose Closes process file pointer
popen Opens process file pointer
readfile Outputs a file
readlink Returns the target of a symbolic link
realpath Returns canonicalized absolute pathname
rename Renames a file
rewind Rewind the position of a file pointer
rmdir Removes directory
set_file_buffer Alias of stream_set_write_buffer()
stat Gives information about a file
symlink Creates a symbolic link
tempnam Create file with unique file name
tmpfile Creates a temporary file
touch Sets access and modification time of file
umask Changes the current umask
unlink Deletes a file

發表留言