ホームページ >バックエンド開発 >PHPチュートリアル >php管理ファイル
php には複数の文件処理関数があります
file_get_contents 文章中の内容を返す文字列。それここでショートカットを使用するのは、外部ファイルが空であるか、数値を保存したい場合があるためです。第 3 章の「PHP による真実」で説明したように、空の文字列と 0 も false に相当します。したがって、この場合は、同一演算子 (3 つの等号) を使用しました。これにより、
値とデータ型の両方が同じであることが保証されますテキスト ファイルはフラット ファイル データベースとして使用できますか?レコードは、各フィールド間にタブ、カンマ、またはその他の区切り文字を入れて別の行に保存されます(http://en.wikipedia.org/ wiki/Flat_file_databaseを参照)。この種のファイルを処理する場合、ループで処理できるように各行を配列に個別に保存すると便利です。 PHP file() 関数は配列を自動的に構築します。 左はパスワードです
david, codeslave chris, bigboss
$contents = file_get_contents('C:/private/filetest01.txt');if ($contents === false) {echo 'Sorry, there was a problem reading the file.';}else {// convert contents to uppercase and displayecho strtoupper($contents);}
注意ここ:
<?php$textfile = 'C:/private/filetest03.txt';if (file_exists($textfile) && is_readable($textfile)) { // read the file into an array called $users $users = file($textfile); // loop through the array to process each line for ($i = 0; $i < count($users); $i++) { // separate each element and store in a temporary array $tmp = explode(', ', $users[$i]); // assign each element of the temporary array to a named array key $users[$i] = array('name' => $tmp[0], 'password' => rtrim($tmp[1])); } }else { echo "Can't open $textfile"; }?><pre class="brush:php;toolbar:false"><?php print_r($users); ?>行が改行文字で終わっている場合、file() 関数はそれを削除しないので、自分で行う必要があります。読み取り/書き込み操作用
fopen(): ファイルを開きます
fgets(): ファイルの内容を読み取ります (通常は一度に 1 行ずつ)
fread(): 指定された量のファイルを読み取りますfwrite(): 書き込みますファイルへ
feof(): ファイルの終わりに達したかどうかを判断しますrewind(): 内部ポインタをファイルの先頭に戻します
fclose(): ファイルを閉じますfopen() 関数は戻り値を返します開いているファイルへの参照。これは他の読み取り/書き込み関数で使用できます。したがって、これは、読み取り用にテキスト ファイルを開く方法です:
$file = fopen('C:/private/filetest03.txt', 'r');
その後、$file を引数として他の関数に渡します。 fgets()、feof()、fclose() など。用fopen读取文件:
'password' => rtrim($tmp[1]));
nl2br 「df250b2156c434f3390392d09b1c9563」を含む文字列を返しますまたは「0c6dc11e160d3b678d68754cc175188a」すべての改行 (rn、nr、n、および r) の前に挿入されます。
<?php// store the pathname of the file$filename = 'C:/private/filetest03.txt';// open the file in read-only mode$file = fopen($filename, 'r');// read the file and store its contents$contents = fread($file, filesize($filename));// close the filefclose($file);// display the contentsecho nl2br($contents);?>
输出:
<?phpecho nl2br("foo isn't\n bar");?>fopen() でファイルの内容を読み取るもう 1 つの方法は、fgets() 関数を使用することです。一度に一行ずつ。これは、ファイルの最後まで読み取るには、while ループを feof() と組み合わせて PHP を使用してファイルを管理する必要があることを意味します。これは、次の行を置き換えることによって行われます
foo isn't<br /> bar
$contents = fread($file, filesize($filename));
書き込み文:
with this (the full script is in fopen_readloop.php)// create variable to store the contents$contents = '';// loop through each line until end of filewhile (!feof($file)) {// retrieve next line, and add to $contents$contents .= fgets($file);}
<?php// if the form has been submitted, process the input textif (array_key_exists('putContents', $_POST)) {// strip backslashes from the input text and save to shorter variable$contents = get_magic_quotes_gpc() ? ?stripslashes($_POST['contents']) : $_POST['contents'];// open the file in write-only mode$file = fopen('C:/private/filetest04.txt', 'w');// write the contentsfwrite($file, $contents);// close the filefclose($file);}?>
fputs() と fwrite() は同じであり、機能都は同じです。 ()打开
fopen() でコンテンツを追加する
form id="writeFile" name="writeFile" method="post" action=""> <p> <label for="contents">Write this to file:</label> <textarea name="contents" cols="40" rows="6" id="contents"></textarea> </p> <p> <input name="putContents" type="submit" id="putContents" value="Write to file" /> </p></form>
$contents を二重引用符で囲み、その前にキャリッジ リターンと改行文字 (rn) を付けていることに注意してください。これにより、新しいコンテンツが新しい行に追加されるようになります。これを Mac
OS X または Linux サーバーで使用する場合は、改行を省略し、代わりに次を使用します:
fwrite($file, "n$contents");
fopen() で新しいファイルを書き込む
同じ名前でファイルが自動的に作成されると便利ですが、希望するものとはまったく逆になる可能性があります。既存のファイルを上書きしないようにするには、x モードで fopen() を使用します。
'x' 作成して書き込み専用に開きます。ファイルポインタをファイルの先頭に置きます。ファイルがすでに存在する場合、fopen() 呼び出しは FALSE を返して失敗し、レベル E_WARNING のエラーが生成されます。
内部ポインタの移動
読み取りおよび書き込み操作は常に内部ポインタが存在する場所から開始されるため、通常は読み取り用のファイルの先頭と、読み取り用のファイルの先頭に配置する必要があります。書き込み用のファイルの終わり。
To move the pointer to the beginning of a file Pass the reference to the open file to rewind() like this:
rewind($file); 倒回
To move the pointer to the end of a file
This is a little more complex. You need to use fseek(), which moves the pointer to a location specified by an offset and a PHP constant. The constant that represents the end of the file is SEEK_END, so an offset of 0 bytes places the pointer where you want it. You also need to pass fseek() a reference to the open file,
so all three arguments together look like this:
fseek($file, 0, SEEK_END);
Exploring the file system
PHP’s file system functions can also open directories (folders) and inspect their contents. From a web designer’s viewpoint, the most practical applications of this are building a drop-down menu of files and creating a unique name for a new file.
array scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] )
List files and directories inside the specified path。
Opening a directory to inspect its contents
// open the directory$folder = opendir('../images');// initialize an array to store the contents$files = array();// loop through the directorywhile (false !== ($item = readdir($folder))) {$files[] = $item;}// close itclosedir($folder);
The readdir() function gets one item at a time and uses an internal pointer in the same
way as the functions used with fopen(). To build a list of the directory’s entire contents,
you need to use a while loop and store each result in an array. The condition for the loop
is contained in the following line:
while (false !== ($item = readdir($folder))) {
The readdir() function returns false when it can find no more items, so to prevent the
loop from coming to a premature end if it encounters an item named 0, for example, you
need to use false with the nonidentical operator (!==).
Each time the while loop runs, $item stores the name of the next file or folder, which is
then added to the $files array. Using this trio of functions isn’t difficult, but the one-line
scandir() is much simpler.
string readdir ( resource dir_handle )
返回目录中下一个文件的文件名。文件名以在文件系统中的排序返回。
请留意下面例子中检查 readdir() 返回值的风格。我们明确地测试返回值是否全等于(值和类型都相同 - 更多信息参见比较运算符)FALSE,否则任何目录项的名称求值为 FALSE 的都会导致循环停止(例如一个目录名为“0”)。
注意意 readdir() 将会返回 . 和 .. 条目。如果不想要它们,只要过滤掉即可
列出当前目录的所有文件并去掉 . 和 ..
<?phpif ($handle = opendir('.')) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { echo "$file\n"; } } closedir($handle);}?>
个人笔记:
opendir只支持本地目录,不支持http:.// 目录 ,如果报错: failed to open dir: not implemented 这是这个问题,
用相对目录会好一点。
Building a drop-down menu of files
<form id="form1" name="form1" method="post" action=""><select name="pix" id="pix"> <option value="">Select an image</option><?phpinclude('../includes/buildFileList5.php');buildFileList5('../images');?></select></form>
<?phpfunction buildFileList5($theFolder) { // Execute code if the folder can be opened, or fail silently if ($contents = @ scandir($theFolder)) { // initialize an array for matching files $found = array(); // Create an array of file types $fileTypes = array('jpg','jpeg','gif','png'); // Traverse the folder, and add filename to $found array if type matches $found = array(); foreach ($contents as $item) { $fileInfo = pathinfo($item); if (array_key_exists('extension', $fileInfo) && in_array($fileInfo['extension'],$fileTypes)) { $found[] = $item; } } // Check the $found array is not empty if ($found) { // Sort in natural, case-insensitive order, and populate menu natcasesort($found); foreach ($found as $filename) { echo "<option value='$filename'>$filename</option>\n"; } } } }?>
After the folder has been opened, each item is
passed to a PHP function called pathinfo(), which returns an associative array with the
following elements:
dirname: The name of the directory (folder)
basename: The filename, including extension (or just the name if it’s a directory)
extension: The filename extension (not returned for a directory)
<?php$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');echo $path_parts['dirname'], "\n";echo $path_parts['basename'], "\n";echo $path_parts['extension'], "\n";echo $path_parts['filename'], "\n"; // since PHP 5.2.0?>
/www/htdocs/inclib.inc.phpphplib.inc
对于一个目录来说,extension是没有的。
Because the extension element is not returned for a directory, you need to use
array_key_exists() before attempting to check its value. The second half of the conditional
statement in line 12 uses in_array() to see if the value of extension matches one
of the file types that you’re looking for. It there’s a match, the filename is added to the
$found array. It’s then just a case of building the 5a07473c87748fb1bf73f23d45547ab8 elements with a foreach loop,
but to add a user-friendly touch, the $found array is first passed to the natcasesort()
function, which sorts the filenames in a case-insensitive order.
In the last chapter I showed you how to create a unique filename by adding a timestamp
or using the date() function to generate the date and time in human-readable format. It
works, but is hardly ideal. A numbered series, such as file01.txt, file02.txt, and so on,
is usually better. The problem is that a PHP script has no way to keep track of a series of
numbers between requests to the server. However, by inspecting the contents of a directory,
you can use pattern matching to find the highest existing number, and assign the next
one in the series.
I’ve turned this into a function called getNextFilename()
The function takes the following three arguments:
The pathname of the directory where you want the new file to be created
The prefix of the filename, which must consist of alphanumeric characters only
The filename extension (without a leading period)
Create series of consecutively numbered files $result"; }?>