Gooday Note Scrap Source Android login
 
작성일 : 11-08-01 13:59
[PHP] 파일과 관련된 php함수
 글쓴이 : 기리 (123.♡.195.24)
조회 : 3,207  
   http://yesyo.com/mintbbs/bbs/board.php?bo_table=php&wr_id=125&page=2 [515]
파일과 관련된 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 121
번호 제   목 글쓴이 날짜 조회
61 [Linux] Port 오픈 확인 (1) 기리 10-27 3021
60 [Linux] 현재 접속자수 보기 netstat (1) 기리 10-12 7539
59 [PHP] 파일과 관련된 PHP 함수 정리 기리 10-07 3275
58 [Java] 트레이 아이콘을 구현하기 (1) 최고관… 09-15 4444
57 [Linux] Apache & MySql 재시작 (1) 기리 09-02 2941
56 [Linux] [LINUX] OS버전 및 IP정보 확인 하기 기리 08-08 3542
55 [PHP] Mobile 기기 확인 기리 08-05 2637
54 [Html] HTML table 테두리 기리 08-04 6404
53 [PHP] 파일과 관련된 php함수 기리 08-01 3208
52 [JavaScript] JavaScript 브라우저 체크 (OS 체크는 보너스) 기리 07-22 3392
51 [JavaScript] window.onunload 기리 07-19 3030
50 [Html] iframe 기리 07-18 2186
49 [MySql] 여러 테이블의 최근 게시물 추출 기리 07-11 8158
48 [PHP] PHP 소켓통신 (1) 기리 07-07 3181
47 [MySql] MySql 쿼리 디버깅을 위한 방법 - MySql 로그 (1) 기리 07-06 4724
 1  2  3  4  5  6  7  8  9