PHP中文件讀、寫、刪的操作(PHP中對(duì)文件和目錄操作)
Jun 13, 2016 pm 12:01 PM
一:目錄操作
首先介紹的是一個(gè)從目錄讀取的函數(shù),opendir(),readdir(),closedir(),使用的時(shí)候是先打開文件句柄,而后迭代列出:
復(fù)制代碼 代碼如下:
$base_dir = "filelist/";
$fso = opendir($base_dir);
echo $base_dir."
" ;
while($flist=readdir($fso)){
echo $flist."
" ;
}
closedir($fso)
?>
這是講返回文件目錄下面的文件已經(jīng)目錄的程序(0文件將返回false).
有時(shí)候需要知道目錄的信息,可以使用dirname($path)和basename($path),分別返回路徑的目錄部分和文件名名稱部分,可用disk_free_space($path)返回看空間空余空間.
創(chuàng)建命令:
mkdir($path,0777)
,0777是權(quán)限碼,在非window下可用umask()函數(shù)設(shè)置.
rmdir($path)
將刪除路徑在$path的文件.
dir -- directory 類也是操作文件目錄的重要類,有3個(gè)方法,read,rewind,close,這是一個(gè)仿面向?qū)ο蟮念?它先使用的是打開文件句柄,然后用指針的方式讀取的.,這里看php手冊(cè):
復(fù)制代碼 代碼如下:
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
[code]
輸出:
Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli
文件的屬性也非常重要,文件屬性包括創(chuàng)建時(shí)間,最后修改時(shí)間,所有者,文件組,類型,大小等
下面我們重點(diǎn)談文件操作.
二:文件操作
讀文件
首先是一個(gè)文件看能不能讀取(權(quán)限問題),或者存在不,我們可以用is_readable函數(shù)獲取信息.:
[code]
$file = 'dirlist.php';
if (is_readable($file) == false) {
die('文件不存在或者無法讀取');
} else {
echo '存在';
}
?>
判斷文件存在的函數(shù)還有file_exists(下面演示),但是這個(gè)顯然無is_readable全面.,當(dāng)一個(gè)文件存在的話可以用
復(fù)制代碼 代碼如下:
$file = "filelist.php";
if (file_exists($file) == false) {
die('文件不存在');
}
$data = file_get_contents($file);
echo htmlentities($data);
?>
但是file_get_contents函數(shù)在較低版本上不支持,可以先創(chuàng)建文件的一個(gè)句柄,然后用指針讀取全部:
復(fù)制代碼 代碼如下:
$fso = fopen($cacheFile, 'r');
$data = fread($fso, filesize($cacheFile));
fclose($fso);
還有一種方式,可以讀取二進(jìn)制的文件:
$data = implode('', file($file));
詳細(xì)學(xué)習(xí)PHP中對(duì)文件和目錄的操作方法
一:引論
在任何計(jì)算機(jī)設(shè)備中,文件是都是必須的對(duì)象,而在web編程中,文件的操作一直是web程序員的頭疼的地方,而,文件的操作在cms系統(tǒng)中這是必須的,非常有用的,我們經(jīng)常遇到生成文件目錄,文件(夾)編輯等操作,現(xiàn)在我把php中的這些函數(shù)做一詳細(xì)總結(jié)并實(shí)例示范如何使用.,關(guān)于對(duì)應(yīng)的函數(shù)詳細(xì)介紹,請(qǐng)查閱php手冊(cè).此處只總結(jié)重點(diǎn).和需要注意的地方.(這在php手冊(cè)是沒有的.)
二:目錄操作
首先介紹的是一個(gè)從目錄讀取的函數(shù),opendir(),readdir(),closedir(),使用的時(shí)候是先打開文件句柄,而后迭代列出:
復(fù)制代碼 代碼如下:
$base_dir = "filelist/";
$fso = opendir($base_dir);
echo $base_dir."
" ;
while($flist=readdir($fso)){
echo $flist."
" ;
}
closedir($fso)
?>
這是講返回文件目錄下面的文件已經(jīng)目錄的程序(0文件將返回false).
有時(shí)候需要知道目錄的信息,可以使用dirname($path)和basename($path),分別返回路徑的目錄部分和文件名名稱部分,可用disk_free_space($path)返回看空間空余空間.
創(chuàng)建命令:
mkdir($path,0777),0777是權(quán)限碼,在非window下可用umask()函數(shù)設(shè)置.
rmdir($path)將刪除路徑在$path的文件.
dir -- directory 類也是操作文件目錄的重要類,有3個(gè)方法,read,rewind,close,這是一個(gè)仿面向?qū)ο蟮念?它先使用的是打開文件句柄,然后用指針的方式讀取的.,這里看php手冊(cè):
復(fù)制代碼 代碼如下:
$d = dir("/etc/php5");
echo "Handle: " . $d->handle . "\n";
echo "Path: " . $d->path . "\n";
while (false !== ($entry = $d->read())) {
echo $entry."\n";
}
$d->close();
?>
輸出:
Handle: Resource id #2
Path: /etc/php5
.
..
apache
cgi
cli
文件的屬性也非常重要,文件屬性包括創(chuàng)建時(shí)間,最后修改時(shí)間,所有者,文件組,類型,大小等
下面我們重點(diǎn)談文件操作.
三:文件操作
讀文件
首先是一個(gè)文件看能不能讀取(權(quán)限問題),或者存在不,我們可以用is_readable函數(shù)獲取信息.:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
if (is_readable($file) == false) {
die('文件不存在或者無法讀取');
} else {
echo '存在';
}
?>
判斷文件存在的函數(shù)還有file_exists(下面演示),但是這個(gè)顯然無is_readable全面.,當(dāng)一個(gè)文件存在的話可以用
復(fù)制代碼 代碼如下:
$file = "filelist.php";
if (file_exists($file) == false) {
die('文件不存在');
}
$data = file_get_contents($file);
echo htmlentities($data);
?>
但是file_get_contents函數(shù)在較低版本上不支持,可以先創(chuàng)建文件的一個(gè)句柄,然后用指針讀取全部:
$fso = fopen($cacheFile, 'r');
$data = fread($fso, filesize($cacheFile));
fclose($fso);
還有一種方式,可以讀取二進(jìn)制的文件:
$data = implode('', file($file));
寫文件
和讀取文件的方式一樣,先看看是不是能寫:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
if (is_writable($file) == false) {
die("我是雞毛,我不能");
}
?>
能寫了的話可以使用file_put_contents函數(shù)寫入:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
if (is_writable($file) == false) {
die('我是雞毛,我不能');
}
$data = '我是可鄙,我想要';
file_put_contents ($file, $data);
?>
file_put_contents函數(shù)在php5中新引進(jìn)的函數(shù)(不知道存在的話用function_exists函數(shù)先判斷一下)低版本的php無法使用,可以使用如下方式:
$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);
替換之.
寫文件的時(shí)候有時(shí)候需要鎖定,然后寫:
復(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)){//寫入字節(jié)流,serialize寫入其他格式
$this->warns('無法寫入緩存文件.');//trigger_error
return false;
}
flock($fso,LOCK_UN);//釋放鎖定
fclose($fso);
return true;
}
復(fù)制,刪除文件
php刪除文件非常easy,用unlink函數(shù)簡單操作:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
$result = @unlink ($file);
if ($result == false) {
echo '蚊子趕走了';
} else {
echo '無法趕走';
}
?>
即可.
復(fù)制文件也很容易:
復(fù)制代碼 代碼如下:
$file = 'yang.txt';
$newfile = 'ji.txt'; # 這個(gè)文件父文件夾必須能寫
if (file_exists($file) == false) {
die ('小樣沒上線,無法復(fù)制');
}
$result = copy($file, $newfile);
if ($result == false) {
echo '復(fù)制記憶ok';
}
?>
可以使用rename()函數(shù)重命名一個(gè)文件夾.其他操作都是這幾個(gè)函數(shù)組合一下就能實(shí)現(xiàn)的.
獲取文件屬性
我說幾個(gè)常見的函數(shù):
獲取最近修改時(shí)間:
復(fù)制代碼 代碼如下:
$file = 'test.txt';
echo date('r', filemtime($file));
?>
返回的說unix的時(shí)間戳,這在緩存技術(shù)常用.
相關(guān)的還有獲取上次被訪問的時(shí)間fileatime(),filectime()當(dāng)文件的權(quán)限,所有者,所有組或其它 inode 中的元數(shù)據(jù)被更新時(shí)間,fileowner()函數(shù)返回文件所有者 $owner = posix_getpwuid(fileowner($file));(非window系統(tǒng)),ileperms()獲取文件的權(quán)限,
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
$perms = substr(sprintf('%o', fileperms($file)), -4);
echo $perms;
?>
filesize()返回文件大小的字節(jié)數(shù):
復(fù)制代碼 代碼如下:
// 輸出類似:somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
獲取文件的全部信息有個(gè)返回?cái)?shù)組的函數(shù)stat()函數(shù):
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
$perms = stat($file);
var_dump($perms);
?>
那個(gè)鍵對(duì)應(yīng)什么可以查閱詳細(xì)資料,此處不再展開.
四:結(jié)束語
上面我簡要的總結(jié)了一下幾個(gè)文件操作,如果您熟練掌握以上列出的函數(shù),已經(jīng)在操作的時(shí)候沒什么大的問題,php文件操作的函數(shù)變化比較快,現(xiàn)在已經(jīng)非常強(qiáng)大了,文件這部分也是學(xué)習(xí)php非常重要的一部分,希望不要忽略.

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
