Post

(PHP) File IO

write

1
2
3
4
5
6
$fname = "open.txt";
if ($fp = fopen($fname, "w")) {
fwrite($fp, "test string\n");    // alias : fputs()
fclose($fp);
}

간결하게 사용하려면 이를 사용하는 것이 좋지만, $fp를 계속 열고 닫아야 하는 경우는 위를 사용하는게 더 빠르다.

1
2
file\_put\_contents("newfile.txt", "contents\n");  // identical to calling fopen - fwrite - fclose

read

1
2
3
4
5
6
7
$fname = "open.txt";
if ($fp = fopen($fname, "r")) {
echo fread($fp, filesize($fname));
echo stream\_get\_contents($fp, filesize($fname));  // mmap 기반
fclose($fp);
}

아래 함수 역시 $fp를 계속 열고 닫아야 한다면 위를 사용하는 편이 좋다.

1
2
echo file\_get\_contents("newfile.txt");    // mmap 기반

이 외에 출력까지 한 번에 해주는 readfile()이 있지만 별로 쓸 필요는 없는 것 같고, php://filter를 사용해 IO data가 filter를 거치도록 만드는 방식도 있는데 자주 사용하지는 않는다.

This post is licensed under CC BY 4.0 by the author.