wilson's story

[펌] php 파일처리 본문

PHP

[펌] php 파일처리

wilson 2008. 7. 17. 16:25
반응형
파일과 관련된 PHP 함수 정리
1. file_exists []
파일을 옮기거나, 복사하거나 파일의 내용을 읽을 때, 파일이 존재하는 지 여부를 체크하는 함수
bool file_exists ( string $filename )
$filename은 파일의 경로와 이름을 인자로 받으며, $filename이 유효한지 여부를 리턴합니다.

2. file Information를 얻고 싶을 때
  • array stat ( string $filename ) [] - 파일의 통계정보를 리턴
  • string filetype ( string $filename ) [] - 파일타입을 리턴합니다. 리턴되는 타입은 fifo, char, dir, block, link, file, socket and unknown 이 리턴됩니다.
  • int filesize ( string $filename ) [] - 파일크기를 리턴합니다.
  • bool is_readable ( string $filename ) [] - 인자로 받은 파일을 읽을 수 있는 지 여부를 리턴합니다.
  • bool is_writable ( string $filename ) [] - 인자로 받는 $filename이 존재하고 쓸 수 있는 경우에 true를 리턴합니다.
  • bool is_executable ( string $filename ) [] - 파일이 실행될 수 있는 지 여부를 리턴합니다.
3. Reading Files, 파일을 읽고 싶을 때
<?php
  $filename = "sample.txt";
  $fileArr = file($filename);
  // or
  $fileStr = file_get_contents($filename);
?>
  • array file ( string $filename [, int $flags [, resource $context ]] ) [] - 전체 파일의 내용을 배열형태로 리턴합니다.
  • string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [, int $maxlen ]]]] ) [] - 전체 파일의 내용을 string으로 리턴합니다.
file_get_contents()가 없는 오래된 PHP에서는 fread를 사용하여서 파일을 읽을 수 있습니다.
<?php
  $filename = "sample.txt"
  $fp = fopen($filename, "rb") or die("fopen failed");
  // 전체 파일을 읽을 때
  $fileStr = fread($fp, filesize($filename));

  // 또는 네트웤을 통해서 파일을 단위별로 읽어들일 때
  while(!feof($fp)) {
    $fileStr .= fgets($fp, 1024);
  }
  fclose($fp) or die("fclose failed");
?>
  • resource fopen ( string $filename , string $mode [, bool $use_include_path [, resource $context ]] ) [] - 파일을 열고 파일 스트림을 리턴합니다.
  • string fread ( resource $handle , int $length ) [] - 인자로 받은 $handle 파일의 내용을 $length만 큼 읽어들입니다.
  • bool fclose ( resource $handle ) [] - 인자로 받은 파일 포인터(스트림)를 닫습니다.
  • bool feof ( resource $handle ) [] - 파일 포인터가 eof(end of file)인 지를 체크합니다.
  • string fgets ( resource $handle [, int $length ] ) [] - 파일포인터로부터 특정 길이만큼 파일의 내용을 읽어들입니다.
4. Writing Files, 파일 쓰기
<?php
  $data = "file Data...";
  file_put_contents('sample.txt', $data) or die("file_put_contents failed");
?>
  • int file_put_contents ( string $filename , mixed $data [, int $flags [, resource $context ]] ) [] - 파일 이름과 파일이 데이타를 인자로 받아서 파일에 데이타를 쓰는 함수입니다. 세 번째 인자로 FILE_APPEND 플래그를 사용하면, 데이타를 덮어쓰는게 아니라 덧붙여 써넣을 수 있습니다.
file_get_contents()와 fopen()처럼 fwirte()를 사용하여 파일을 쓸 수도 있습니다.
<?php
  $data = "file Data...";
  $fp = fopen("sample.txt", wb+) or die("fopen failed");
  if(flock($fp, LOCK_EX)) {
    fwrite($fp, $data) or die("fwrite failed");
    flock($fp, LOCK_UN);
  }
  fclose($fp) or die("fclose failed");
?>
  • int fwrite ( resource $handle , string $string [, int $length ] ) [] - 파일 스트림과 파일에 쓸 데이타를 인자로 받아서 파일에 데이타를 씁니다. 세 번째 인자가 주어진 경우 주어진 길이까지만 파일이 써지게 됩니다.
  • bool flock ( resource $handle , int $operation [, int &$wouldblock ] ) [] - 파일의 스트림과 $operation을 인자로 받아서 파일 락을 설정합니다. LOCK_EX(exclusive lock), LOCK_SH(shared lock), LOCK_UN(unlock), LOCK_NB를 설정할 수 있습니다.

    파일을 쓸 때 다른 프로그램이 동시에 하나의 파일에 엑세스해서 파일이 헝클어지는 것을 방지하기 위해서 lock을 설정합니다. php에서의 lock만 해당하며 php 외의 다른 프로그램에서 접근하는 것까지 lock을 걸지는 못합니다.
5. Removing file lines. 파일의 라인을 삭제하기
<?php
  $filename = "sample.txt";
  //file을 읽어들여서 배열형태로 $data를 읽어들입니다.
  $data = file($filename) or die("file failed"); 
  // 배열의 세 번째 라인을 삭제합니다.
  unset($data[2]); 
  // 배열을 인덱스를 새로 생성합니다.
  $data = array_values($data);
  file_put_contents($filename, implode($data)) or die("fipe_put_contents failed");
?>
  • void unset ( mixed $var [, mixed $var [, mixed $... ]] ) [] - 값을 삭제하는 함수로 인자의 타입에 따라서 다르게 동작합니다.
  • array array_values ( array $input ) [] - 입력 배열의 모든 값을 숫자 키값과 함께 리턴합니다.
6. Processing Directories 디렉토리 다루기
<?php
  $dir = "./sample";
  // 디렉토리에 들어있는 파일/디렉토리들을 배열형태로 리턴합니다.
  $fileList = scandir($dir) or die("scandir failed");
  // 배열을 루프로 돌면서 디렉토리에 들어있는 파일들에 작업을 수행합니다.
  foreach ($fileList as $file) {
    // 실제 파일인지 여부를 체크합니다.
    if( is_file("$dir/$file") && $file != '.' && $file != '..') {
      //...
    }
  }
?>
  • array scandir ( string $directory [, int $sorting_order [, resource $context ]] ) [] - 디렉토리안에 있는 파일과 디렉토리를 배열로 리턴합니다.
<?php
  $dir = "./sample";
  // DirectoryIterator를 생성합니다.
  $iterator = new DirectoryIterator($dir);
  // 내부의 iterator를 첫 element로 이동시킵니다.
  $iterator->rewind();
  // current element가 있는 지 여부를 확인한 후
  while($iterator->vaild()) {
    // 디렉토리가 아닌 실제 파일인지를 확인한 후 실제 작업을 수행합니다.
    if($iterator->isFile() && !$iterator->isDot()) {
     // ...
    }
    // 다음 element로 iterator를 넘깁니다.
    $iterator->next();
  }
?>
DirectoryIterator($path)는 $path를 인자로 받아서 생성하며 디렉토리의 파일/디렉토리를 이동하며 파일정보를 확인하거나 작업을 할 수 있는 클래스입니다.

7. Renaming  Files and Directories 디렉토리 다루기
<?php
   $oldFileName = "oldName.txt";
   $newFileName = "newName.txt";

   // 파일이 있는 지 여부를 체크합니다.
   if(file_exists($oldFileName)) {
     // 대상 파일의 이름을 수정합니다.
     rename($oldFileName, $newFileName) or die("Renaming file is failed.");
   } else {
      die("Cannot find file '$oldFileName'");
   }
?>
rename()은 파일이름 변경 및 파일의 위치 이동을 동시에 실행할 수 있는 함수입니다. 인자는 변경할 원 파일의 이름과 변경 대상이 되는 파일 두 개를 인자로 받습니다.

관련자료: PHP Programming SOLUTIONS 6장 "Working with Files and Directories" 책 보면서 정리한 내용입니다.
반응형