国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊(cè) PHP中文件讀、寫、刪的操作(PHP中對(duì)文件和目錄操作)

PHP中文件讀、寫、刪的操作(PHP中對(duì)文件和目錄操作)

Jun 13, 2016 pm 12:01 PM
php one introduce Write function delete and right operate document yes of Table of contents read first

一:目錄操作
   首先介紹的是一個(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ù)簡(jiǎn)單操作:

復(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é)束語(yǔ)
上面我簡(jiǎn)要的總結(jié)了一下幾個(gè)文件操作,如果您熟練掌握以上列出的函數(shù),已經(jīng)在操作的時(shí)候沒什么大的問題,php文件操作的函數(shù)變化比較快,現(xiàn)在已經(jīng)非常強(qiáng)大了,文件這部分也是學(xué)習(xí)php非常重要的一部分,希望不要忽略.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to get the current session ID in PHP? How to get the current session ID in PHP? Jul 13, 2025 am 03:02 AM

The method to get the current session ID in PHP is to use the session_id() function, but you must call session_start() to successfully obtain it. 1. Call session_start() to start the session; 2. Use session_id() to read the session ID and output a string similar to abc123def456ghi789; 3. If the return is empty, check whether session_start() is missing, whether the user accesses for the first time, or whether the session is destroyed; 4. The session ID can be used for logging, security verification and cross-request communication, but security needs to be paid attention to. Make sure that the session is correctly enabled and the ID can be obtained successfully.

PHP get substring from a string PHP get substring from a string Jul 13, 2025 am 02:59 AM

To extract substrings from PHP strings, you can use the substr() function, which is syntax substr(string$string,int$start,?int$length=null), and if the length is not specified, it will be intercepted to the end; when processing multi-byte characters such as Chinese, you should use the mb_substr() function to avoid garbled code; if you need to intercept the string according to a specific separator, you can use exploit() or combine strpos() and substr() to implement it, such as extracting file name extensions or domain names.

How do you perform unit testing for php code? How do you perform unit testing for php code? Jul 13, 2025 am 02:54 AM

UnittestinginPHPinvolvesverifyingindividualcodeunitslikefunctionsormethodstocatchbugsearlyandensurereliablerefactoring.1)SetupPHPUnitviaComposer,createatestdirectory,andconfigureautoloadandphpunit.xml.2)Writetestcasesfollowingthearrange-act-assertpat

How to split a string into an array in PHP How to split a string into an array in PHP Jul 13, 2025 am 02:59 AM

In PHP, the most common method is to split the string into an array using the exploit() function. This function divides the string into multiple parts through the specified delimiter and returns an array. The syntax is exploit(separator, string, limit), where separator is the separator, string is the original string, and limit is an optional parameter to control the maximum number of segments. For example $str="apple,banana,orange";$arr=explode(",",$str); The result is ["apple","bana

JavaScript Data Types: Primitive vs Reference JavaScript Data Types: Primitive vs Reference Jul 13, 2025 am 02:43 AM

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How to pass a session variable to another page in PHP? How to pass a session variable to another page in PHP? Jul 13, 2025 am 02:39 AM

In PHP, to pass a session variable to another page, the key is to start the session correctly and use the same $_SESSION key name. 1. Before using session variables for each page, it must be called session_start() and placed in the front of the script; 2. Set session variables such as $_SESSION['username']='JohnDoe' on the first page; 3. After calling session_start() on another page, access the variables through the same key name; 4. Make sure that session_start() is called on each page, avoid outputting content in advance, and check that the session storage path on the server is writable; 5. Use ses

How does PHP handle Environment Variables? How does PHP handle Environment Variables? Jul 14, 2025 am 03:01 AM

ToaccessenvironmentvariablesinPHP,usegetenv()orthe$_ENVsuperglobal.1.getenv('VAR_NAME')retrievesaspecificvariable.2.$_ENV['VAR_NAME']accessesvariablesifvariables_orderinphp.iniincludes"E".SetvariablesviaCLIwithVAR=valuephpscript.php,inApach

See all articles