PHP中文件讀、寫(xiě)、刪的操作(PHP中對(duì)文件和目錄操作)
Jun 13, 2016 pm 12:01 PM
一:目錄操作
首先介紹的是一個(gè)從目錄讀取的函數(shù),opendir(),readdir(),closedir(),使用的時(shí)候是先打開(kāi)文件句柄,而后迭代列出:
復(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),分別返回路徑的目錄部分和文件名名稱(chēng)部分,可用disk_free_space($path)返回看空間空余空間.
創(chuàng)建命令:
mkdir($path,0777)
,0777是權(quán)限碼,在非window下可用umask()函數(shù)設(shè)置.
rmdir($path)
將刪除路徑在$path的文件.
dir -- directory 類(lèi)也是操作文件目錄的重要類(lèi),有3個(gè)方法,read,rewind,close,這是一個(gè)仿面向?qū)ο蟮念?lèi),它先使用的是打開(kāi)文件句柄,然后用指針的方式讀取的.,這里看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í)間,所有者,文件組,類(lèi)型,大小等
下面我們重點(diǎn)談文件操作.
二:文件操作
讀文件
首先是一個(gè)文件看能不能讀取(權(quán)限問(wèn)題),或者存在不,我們可以用is_readable函數(shù)獲取信息.:
[code]
$file = 'dirlist.php';
if (is_readable($file) == false) {
die('文件不存在或者無(wú)法讀取');
} else {
echo '存在';
}
?>
判斷文件存在的函數(shù)還有file_exists(下面演示),但是這個(gè)顯然無(wú)is_readable全面.,當(dāng)一個(gè)文件存在的話(huà)可以用
復(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è)是沒(méi)有的.)
二:目錄操作
首先介紹的是一個(gè)從目錄讀取的函數(shù),opendir(),readdir(),closedir(),使用的時(shí)候是先打開(kāi)文件句柄,而后迭代列出:
復(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),分別返回路徑的目錄部分和文件名名稱(chēng)部分,可用disk_free_space($path)返回看空間空余空間.
創(chuàng)建命令:
mkdir($path,0777),0777是權(quán)限碼,在非window下可用umask()函數(shù)設(shè)置.
rmdir($path)將刪除路徑在$path的文件.
dir -- directory 類(lèi)也是操作文件目錄的重要類(lèi),有3個(gè)方法,read,rewind,close,這是一個(gè)仿面向?qū)ο蟮念?lèi),它先使用的是打開(kāi)文件句柄,然后用指針的方式讀取的.,這里看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í)間,所有者,文件組,類(lèi)型,大小等
下面我們重點(diǎn)談文件操作.
三:文件操作
讀文件
首先是一個(gè)文件看能不能讀取(權(quán)限問(wèn)題),或者存在不,我們可以用is_readable函數(shù)獲取信息.:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
if (is_readable($file) == false) {
die('文件不存在或者無(wú)法讀取');
} else {
echo '存在';
}
?>
判斷文件存在的函數(shù)還有file_exists(下面演示),但是這個(gè)顯然無(wú)is_readable全面.,當(dāng)一個(gè)文件存在的話(huà)可以用
復(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));
寫(xiě)文件
和讀取文件的方式一樣,先看看是不是能寫(xiě):
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
if (is_writable($file) == false) {
die("我是雞毛,我不能");
}
?>
能寫(xiě)了的話(huà)可以使用file_put_contents函數(shù)寫(xiě)入:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
if (is_writable($file) == false) {
die('我是雞毛,我不能');
}
$data = '我是可鄙,我想要';
file_put_contents ($file, $data);
?>
file_put_contents函數(shù)在php5中新引進(jìn)的函數(shù)(不知道存在的話(huà)用function_exists函數(shù)先判斷一下)低版本的php無(wú)法使用,可以使用如下方式:
$f = fopen($file, 'w');
fwrite($f, $data);
fclose($f);
替換之.
寫(xiě)文件的時(shí)候有時(shí)候需要鎖定,然后寫(xiě):
復(fù)制代碼 代碼如下:
function cache_page($pageurl,$pagedata){
if(!$fso=fopen($pageurl,'w')){
$this->warns('無(wú)法打開(kāi)緩存文件.');//trigger_error
return false;
}
if(!flock($fso,LOCK_EX)){//LOCK_NB,排它型鎖定
$this->warns('無(wú)法鎖定緩存文件.');//trigger_error
return false;
}
if(!fwrite($fso,$pagedata)){//寫(xiě)入字節(jié)流,serialize寫(xiě)入其他格式
$this->warns('無(wú)法寫(xiě)入緩存文件.');//trigger_error
return false;
}
flock($fso,LOCK_UN);//釋放鎖定
fclose($fso);
return true;
}
復(fù)制,刪除文件
php刪除文件非常easy,用unlink函數(shù)簡(jiǎn)單操作:
復(fù)制代碼 代碼如下:
$file = 'dirlist.php';
$result = @unlink ($file);
if ($result == false) {
echo '蚊子趕走了';
} else {
echo '無(wú)法趕走';
}
?>
即可.
復(fù)制文件也很容易:
復(fù)制代碼 代碼如下:
$file = 'yang.txt';
$newfile = 'ji.txt'; # 這個(gè)文件父文件夾必須能寫(xiě)
if (file_exists($file) == false) {
die ('小樣沒(méi)上線(xiàn),無(wú)法復(fù)制');
}
$result = copy($file, $newfile);
if ($result == false) {
echo '復(fù)制記憶ok';
}
?>
可以使用rename()函數(shù)重命名一個(gè)文件夾.其他操作都是這幾個(gè)函數(shù)組合一下就能實(shí)現(xiàn)的.
獲取文件屬性
我說(shuō)幾個(gè)常見(jiàn)的函數(shù):
獲取最近修改時(shí)間:
復(fù)制代碼 代碼如下:
$file = 'test.txt';
echo date('r', filemtime($file));
?>
返回的說(shuō)unix的時(shí)間戳,這在緩存技術(shù)常用.
相關(guān)的還有獲取上次被訪(fǎng)問(wè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ù)制代碼 代碼如下:
// 輸出類(lèi)似: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ì)資料,此處不再展開(kāi).
四:結(jié)束語(yǔ)
上面我簡(jiǎn)要的總結(jié)了一下幾個(gè)文件操作,如果您熟練掌握以上列出的函數(shù),已經(jīng)在操作的時(shí)候沒(méi)什么大的問(wèn)題,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

The key to setting up PHP is to clarify the installation method, configure php.ini, connect to the web server and enable necessary extensions. 1. Install PHP: Use apt for Linux, Homebrew for Mac, and XAMPP recommended for Windows; 2. Configure php.ini: Adjust error reports, upload restrictions, etc. and restart the server; 3. Use web server: Apache uses mod_php, Nginx uses PHP-FPM; 4. Install commonly used extensions: such as mysqli, json, mbstring, etc. to support full functions.

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech

PHPblockcommentsareusefulforwritingmulti-lineexplanations,temporarilydisablingcode,andgeneratingdocumentation.Theyshouldnotbenestedorleftunclosed.BlockcommentshelpindocumentingfunctionswithPHPDoc,whichtoolslikePhpStormuseforauto-completionanderrorche

Comments cannot be careless because they want to explain the reasons for the existence of the code rather than the functions, such as compatibility with old interfaces or third-party restrictions, otherwise people who read the code can only rely on guessing. The areas that must be commented include complex conditional judgments, special error handling logic, and temporary bypass restrictions. A more practical way to write comments is to select single-line comments or block comments based on the scene. Use document block comments to explain parameters and return values at the beginning of functions, classes, and files, and keep comments updated. For complex logic, you can add a line to the previous one to summarize the overall intention. At the same time, do not use comments to seal code, but use version control tools.

The key to writing good comments is to explain "why" rather than just "what was done" to improve the readability of the code. 1. Comments should explain logical reasons, such as considerations behind value selection or processing; 2. Use paragraph annotations for complex logic to summarize the overall idea of functions or algorithms; 3. Regularly maintain comments to ensure consistency with the code, avoid misleading, and delete outdated content if necessary; 4. Synchronously check comments when reviewing the code, and record public logic through documents to reduce the burden of code comments.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.
