ファイルのデータ表示
<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");
$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");
$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>