YesYo.com MintState Forums
뒤로    YesYo.com MintState BBS > Tech > PHP
검색
멤버이름    오토
비밀번호 
 

파일과 관련된 PHP 함수

페이지 정보

작성자 MintState 댓글 0건 조회 16,328회 작성일 09-02-17 11:45

본문

파일과 관련된 PHP 함수

깔끔하게 정리된 포스팅을 보고 스크랩 합니다.
파일관련함수는 요즘에 몇몇함수를 빼놓고는 사용빈도가 떨어져서 생각이 잘 않났는데 이 포스팅을 보고 다시 한번 공부해 봅니다.
예전에 파일디비로 프로그램 짤때는 많이 썼죠 ^^
원본은 : http://okjungsoo.tistory.com/entry/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'");
   }
?>

bool rename ( string $oldname , string $newname [, resource $context ] ) - 파일이름 변경 및 파일의 위치 이동을 동시에 실행할 수 있는 함수입니다. 인자는 변경할 원 파일의 이름과 변경 대상이 되는 파일 두 개를 인자로 받습니다.

7. filemtime 파일 생성(수정) 시간
<?php
// outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23.

$filename = 'somefile.txt';
if (file_exists($filename)) {
    echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename));
}
?>



P.S>
1. mixed end ( array &$array ) - Array의 내부 포인터를 마지막 element로 이동시킵니다. end($arr)를 출력하면 Array의 마지막 값이 출력됩니다.
2. $arr[] = 4; // array에 index 없이 값을 할당하는 경우 array의 마지막 index로 값이 할당되네요.

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

댓글목록

등록된 댓글이 없습니다.

Total 165건 2 페이지
PHP 목록
번호 제목 글쓴이 조회 날짜
140 MintState 18342 07-02
139 MintState 16340 06-30
138 MintState 22452 04-28
137 MintState 15910 02-12
136 MintState 28701 01-13
135 MintState 16466 10-09
134 MintState 18198 08-25
133 MintState 15237 07-28
132 MintState 18585 04-28
131 MintState 23539 04-09
130 MintState 16050 04-06
129 MintState 13354 02-25
128 MintState 16604 02-25
127 MintState 12346 02-23
126 MintState 11579 02-23
125 MintState 15998 02-23
열람중 MintState 16329 02-17
123 MintState 15313 02-17
122 MintState 16926 11-17
121 MintState 22247 11-17
120 MintState 12215 11-17
119 MintState 17185 11-17
118 MintState 13789 11-17
117 MintState 16129 11-10
116 MintState 14455 11-10
게시물 검색
모바일 버전으로 보기
CopyRight ©2004 - 2024, YesYo.com MintState. ™