fopen/fclose関数の使い方

fopen/fclose関数の使い方 PHP言語リファレンス
fopen/fclose関数の使い方
zucksadnetwork

fopen/fclose関数とは?

fopen関数とfclose関数は、PHPでファイルを開いたり閉じたりするための関数です。

fopen/fclose関数の概要

fopen関数の基本的な書式は、次のとおりです。

PHP

resource fopen(string $filename, string $mode);
  • string $filename:ファイル名
  • string $mode:アクセスモード

fopen関数は、ファイル名とアクセスモードを指定して、ファイルハンドルを返します。ファイルハンドルは、ファイルへの操作を行うためのオブジェクトです。

fclose関数の基本的な書式は、次のとおりです。

PHP

void fclose(resource $handle);
  • resource $handle:ファイルハンドル

fclose関数は、ファイルハンドルを閉じます。

fopen/fclose関数の書き方

fopen/fclose関数の書き方は、次のとおりです。

  1. ファイル名とアクセスモードを用意します。
  2. fopen関数を呼び出して、ファイルハンドルを取得します。
  3. ファイルハンドルを使用して、ファイルの操作を行います。
  4. fclose関数を呼び出して、ファイルハンドルを閉じます。

PHP

// ファイル名の用意
$filename = "example.txt";

// アクセスモードの用意
$mode = "w";

// ファイルハンドルの取得
$handle = fopen($filename, $mode);

// ファイルの書き込み
fwrite($handle, "Hello, world!");

// ファイルハンドルの閉じ
fclose($handle);

このコードは、example.txtというファイルを書き込みモードで開き、”Hello, world!”と書き込んでから、閉じるコードです。

fopen/fclose関数の作成・使用方法

fopen/fclose関数は、次の2つの方法で使用できます。

  • ファイル操作の処理をまとめた関数として作成する
  • ファイル操作の処理を直接行う

PHP

// ファイル操作の処理をまとめた関数として作成
function write_file(string $filename, string $content) {
    // ファイルハンドルの取得
    $handle = fopen($filename, "w");

    // ファイルの書き込み
    fwrite($handle, $content);

    // ファイルハンドルの閉じ
    fclose($handle);
}

// ファイル操作の処理を直接行う
$filename = "example.txt";
$content = "Hello, world!";

// ファイルハンドルの取得
$handle = fopen($filename, "w");

// ファイルの書き込み
fwrite($handle, $content);

// ファイルハンドルの閉じ
fclose($handle);

fopen/fclose関数のスクリプトサンプル

次のスクリプトは、fopen/fclose関数を使用して、さまざまなファイル操作を行っています。

PHP

// ファイルを読み込む
$filename = "example.txt";

// ファイルハンドルの取得
$handle = fopen($filename, "r");

// ファイルの読み込み
$content = fread($handle, filesize($filename));

// ファイルハンドルの閉じ
fclose($handle);

// ファイルの内容を表示
echo $content;

// ファイルを書き込む
$filename = "example.txt";
$content = "Hello, world!";

// ファイルハンドルの取得
$handle = fopen($filename, "w");

// ファイルの書き込み
fwrite($handle, $content);

// ファイルハンドルの閉じ
fclose($handle);

// ファイルを削除する
$filename = "example.txt";

// ファイルの削除
unlink($filename);

このコードは、example.txtというファイルを読み込み、”Hello, world!”と書き込み、削除するコードです。

fopen/fclose関数特有の事柄・注意点

  • fopen関数で指定できるアクセスモードは、次のとおりです。
r : ファイルを読み取り専用で開く
w : ファイルを書き込み専用で開く
a : ファイルを追記モードで開く
x : ファイルを上書きモードで開く
  • ファイルハンドルは、クローズするまでは、他の関数で使用することはできません。