0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

PHPのビルトイン関数まとめ(ファイル関連)

Posted at

はじめに

PHPの学習をはじめたので、アウトプットとして記載します。

ビルトイン関数とは

ビルトインとはあらかじめ組み込まれていることを意味します。
関数は自身で作ることができますが、PHPにはあらかじめ用意された関数があり、それらをビルトイン関数と呼びます。

PHPのビルトイン関数(ファイル関連)

fopen:ファイルを開く、fclose:ファイルを閉じる、fwrite:ファイルに書き込む

phpファイル
$fp = fopen('names.txt', 'w'); //names.txtを'w'(書き込みモード)で開く、ファイルがない場合は作られる

fwrite($fp, "taro\n"); //テキストファイルにtaroの文字を書き込む、\nは改行の意味

fclose($fp); //開いたファイルを閉じる

fopenのオプション

phpファイル
$fp = fopen('names.txt', 'w'); //'w'はwrite(書き込みモード)の意味
$fp = fopen('names.txt', 'a'); //'a'はappend(追加するモード)の意味
$fp = fopen('names.txt', 'r'); //'r'はread(読み込みモード)の意味

fread:サイズを指定してファイルを読み込む、filesize:ファイルサイズを調べる

phpファイル
$fp = fopen('names.txt', 'r');
$contents = fread($fp, filesize('names.txt')); //$contentsにname.txtの中身を代入
fclose($fp);
echo $contents;

fgets:ファイルを1行ずつ読み込む

phpファイル
$fp = fopen('names.txt', 'r');
while (($line = fgets($fp))!== false) { 
  echo $line;
}  //names.txtを1行ずつ読み込み、読み込み終了時に読み込みした内容を表示する
fclose($fp);

file_put_contents:fopenを使わず、ファイルに書き込む

phpファイル
$contents = "taro\njiro\nsaburo\n";
file_put_contents('names.txt', $contents); //names.txtファイルの中にtaro\njiro\nsaburo\nが書き込まれる

file_get_contents:fopenを使わず、ファイルを読み込む

phpファイル
$contents = file_get_contents('names.txt'); //names.txtファイルの中身を$contentsの中に入れることができる

file:ファイルの中身を配列にする

phpファイル
$lines = file('names.txt', FILE_IGNORE_NEW_LINES); //$linesはnames.txtの中身を順に入れた配列となる
//FILE_IGNORE_NEW_LINESは末尾の改行をなくすオプション

opendir:ディレクトリを操作できるようにする、readdir:ディレクトリの中身を1行ずつ読み込む

phpファイル
file_put_contents('data/taro.txt', "taro\n");
file_put_contents('data/jiro.txt', "jiro\n");

$dp = opendir('data');
while(($item = readdir($dp)) !== false) {
  if ($item === '.' || $item == '..'){
    continue;
  }  //dataディレクトリの中身(ファイル)が存在する限り$itemに代入する、ただし、'.'や'..'は除く
  echo $item . PHP_EOL;
}

glob:指定したパスを配列として取り出す、basename:ファイル名だけ取り出せる

phpファイル
foreach (glob('data/*.txt') as $item) { //globで取り出したファイルを要素とする配列の要素を$itemに代入する
  echo $item . PHP_EOL; // ファイルを表示する、表示はdata/〇〇.txtの形式
  echo basename($item) . PHP_EOL; // ファイルを表示する、表示は〇〇.txtの形式
}

file_exits:ディレクトリやファイルが存在する時true、存在しない時falseを返す
is_writable:ファイルが書き込み可能な時true、書き込み不可の時falseを返す
is_readable:ファイルが読み込み可能な時true、読み込み不可の時falseを返す

phpファイル
file_exists('data'); //dataディレクトリもしくはdataファイルがあれば、true
is_writable('data/taro.txt'); //dataディレクトリ内のtaro.txtが書き込み可能ならtrue
is_readable('data/taro.txt'); //dataディレクトリ内のtaro.txtが読み込み可能ならtrue

参考

ドットインストール

最後に

本投稿が初学者の復習の一助となればと幸いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?