前回は、データベースを利用して、データを扱うコードを作成しました。
データを管理する方法は。ほかにもファイルを利用する方法があります。
PHPでは、組み込み関数を使いファイルに関する情報を調べたり、
ファイルの読み書きができます。
ファイルに関する情報を調べるのにはstat()関数を使います。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>ファイル情報を調べてみる</title> <link rel="stylesheet" href="../style.css"> </head> <body> <table border="2"> <tr bgcolor="#a0a0a0"> <th>番号</th> <th>値</th> </tr> <?php $st = stat("index.php"); foreach( $st as $name => $value ){ echo "<tr>" . "<td>\$name = " . $name . "<td>\$value = " . $value; } ?> </table> </body> </html> |
stat()関数にファイル名を引数とすることで、
ファイルに関する情報を得ることができます。
番号 | キー | 説明 |
---|---|---|
0 | dev | デバイス番号 |
1 | ino | inode番号(ファイル識別番号) |
2 | mode | inodeプロテクトモード |
3 | nlink | リンク数 |
4 | uid | ユーザーID |
5 | gid | グループID |
6 | rdev | デバイスの種類 |
7 | size | ファイルサイズ |
8 | atime | 最終サクセス時刻 |
9 | mtime | 最終修正時刻 |
10 | ctime | 作成時刻 |
11 | blksize | ブロックサイズ(windowsは -1) |
12 | blocks | ブロック数(windowsは -1) |
ディレクトリを調べる
Windowsでは、ファイルを整理する概念としてフォルダを使います。
フォルダは、プログラミングの世界ではディレクトリといいます。
PHPの関数を使いディレクトリの情報を調べてみます。
opendir()関数でディレクトリ情報にアクセスし、
readdir()関数でそのディレクトリにある
ディレクトリ名・ファイル名を読み込むことができ、
最後にclosedir()関数を使い終了します。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>PHPでディレクトリ調査</title> <link rel="stylesheet" href="../style.css"> </head> <body> <?php //ディレクトリ情報にアクセス $curDir = opendir("."); //ディレクトリ名・ファイル名がfalseとなるまで while( $name = readdir($curDir) ){ //名前を表示 echo $name . "<br>"; } closedir($curDir); ?> </body> </html> |
「..」は一つ上のディレクトリを表しています。
関数名 | 戻り値 | 説明 |
---|---|---|
opendir(string $path) | resource | ディレクトリをオープン |
readdir(resource $dir) | string | ディレクトリのファイル名を1つ読む |
closedir(resource $dir) | なし | ディレクトリをクローズ |
詳細なファイル情報
is_dir()関数で、ディレクトリとファイルの区別を調べ
is_writeable()関数で書き込み可能かどうか
is_readable()関数で読込可能かどうかを調べられます。
サンプルコードの実行結果はこちら
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
<!doctype html> <html> <head> <meta charset="utf-8"> <title>PHPでディレクトリ調査</title> <link rel="stylesheet" href="../style.css"> </head> <body> <table border="2"> <tr> <th>name</th> <th>directory</th> <th>writeable</th> <th>readable</th> </tr> <?php //ディレクトリ情報にアクセス $curDir = opendir("."); //ディレクトリ名・ファイル名がfalseとなるまで while( $name = readdir($curDir) ){ $isd = is_dir( $name ) ? "Directory": "File"; $isw = is_writeable( $name ) ? "OK": "NG"; $isr = is_readable( $name ) ? "OK": "NG"; echo "<tr>" . "<td>{$name}</td>" . "<td>{$isd}</td>" . "<td>{$isw}</td>" . "<td>{$isr}</td>" . "</tr>"; } closedir($curDir); ?> </table> </body> </html> |
関数名 | 戻り値 | 説明 |
---|---|---|
is_dir(string $filename) | boolean | ディレクトリかどうか判定 |
is_readable(string $filename) | boolean | 読み込み可能かどうか判定 |
is_writeable(string $filename) | boolean | 書き込み可能かどうか判定 |