Hope is a Dream. Dream is a Hope.

非公開ブログは再開しました。

いきおいでPHPを勉強する。その8

ファイルのデータ表示

<html>
<head>
<title>ファイルのデータを表示する</title>
</head>
<body>
<?php
// ファイル名
$file_name = "test.txt";

// ファイルを読み取りモードで開く
$file = @fopen($file_name, "r") or die("OPENエラー $file_name");

// ファイルをロックする(共有ロック)
flock($file, LOCK_SH);

// ファイルのデータを表示する
while (!feof($file)) {
    $string = fgets($file, 1000);
    echo $string."<br>";
}

// ロックを開放する
flock($file, LOCK_UN);

// ファイルを閉じる
fclose($file);
?>
</body>
</html>

 ファイルのデータを1バイト表示

<html>
<head>
<title>ファイルのデータを1バイト表示する</title>
</head>
<body>
<?php
// ファイル名
$file_name = "test.txt";

// ファイルを読み取りモードで開く
$file = fopen($file_name, "r") or die("OPENエラー $file_name");

// ファイルのデータを1バイト取得する
$string = fgetc($file);

// 読み込んだデータを表示する
echo "<p>ファイルの内容:".$string;

// ファイルを閉じる
fclose($file);
?>
</body>
</html>

ファイルから指定バイト数だけ表示

<html>
<head>
<title>ファイルから指定バイト数だけ表示する</title>
</head>
<body>
<?php
// ファイル名
$file_name = "test.txt";

// ファイルを読み取りモードで開く
$file = fopen($file_name, "r") or die("OPENエラー $file_name");

// ファイルのデータを10バイト取得する
$string = fread($file, 10);

// 読み込んだデータを表示する
echo "<p>ファイルの内容:".$string;

// ファイルを閉じる
fclose($file);
?>
</body>
</html>

ファイルのデータをまとめて表示する

<html>
<head>
<title>ファイルのデータをまとめて表示する</title>
</head>
<body>
<?php
// ファイル名
$file_name = "test.txt";

// ファイルを読み取りモードで開く
$file = fopen($file_name, "r") or die("OPENエラー $file_name");

// ファイルのデータをまとめて取得する
$string = fread($file, filesize($file_name));

// 読み込んだデータを表示する
echo "<p>ファイルの内容:".$string;

// ファイルを閉じる
fclose($file);

// ファイルのデータをひとつの文字列で取得する
$string = file_get_contents($file_name);
echo "<p>ファイルの内容:".$string;

// ファイルを配列に格納する
$string = file($file_name);
echo "<p>ファイルの内容:";
print_r($string);
?>
</body>
</html>

ファイルを使ったアクセスカウンタ

<html>
<head>
<title>ファイルを使ったアクセスカウンタ</title>
</head>
<body>
<?php
// カウンタファイル
$cnt_file = "count.dat";
// カウンタ桁数
$cnt_len = 10;

// カウンタファイルが存在すればカウンタ値を読み取る
if (file_exists($cnt_file)) {

    $file = fopen($cnt_file, "r+");
    $count = fgets($file, $cnt_len);
    $count = $count + 1;
}
// カウンタファイルが存在しないなら新規作成する
else {
    $file = fopen($cnt_file, "w");
    $count = 1;
    
}
// ファイルポインタを先頭にセットする
rewind($file);

// ファイルをロックする
flock($file, LOCK_EX);

// カウンタ値を書き込む
fputs($file, $count, $cnt_len);

// ファイルのロックを解除する
flock($file, LOCK_UN);

// ファイルを閉じる
fclose($file);

// カウンタ値を出力する
echo $count;
?>
</body>
</html>