회원가입∴아이디/비번찾기
홈으로


PHP 파일처리
15년 전
파일과 관련된 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" 책 보면서 정리한 내용입니다.
추천추천 : 419 추천 목록
번호 제목
2,891
입력 필드에서 특정단어(예:#err)가 포함되었을 때 실시간 감지 및 경고창 띄우기
2,890
데이터베이스 최적화와 쿼리 효율성을 높이 검색 성능을 개선하는 방법
2,889
간단한 게시판 만들기
2,888
PHP의 php.ini 파일에서 설정할 수 있는 주요 항목들을 카테고리별로 정리
2,887
유튜브 동영상의 썸네일 이미지를 체크하여 유효한 영상이아닐때 연결된 체크박스를 자동으로 체크
2,886
이미지 URL이 유효하지 않을 때, 해당 이미지와 연결된 체크박스를 자동으로 체크
2,885
HTTPS로 접속한 사용자를 강제로 HTTP로 리디렉션 하려면
2,884
PHP에서 MP3 파일을 직접 읽고 스트리밍 하기
2,883
현재 페이지가 location.reload()에 의해 새로고침되었는지
2,882
텍스트 파일을 읽고, 각 줄의 끝에서 6글자를 삭제한 후, 결과를 새로운 파일에 저장합니다.
2,881
cURL을 사용하여 리다이렉트를 따라가 최종 URL 가져오기
2,880
[PHP] $_SERVER 환경변수
2,879
10진수 <-> 16진수 변환기 PHP소스
2,878
텍스트에 직접 그라데이션 색상을 적용하려면?
2,877
CSS를 사용하여 요소의 내용물에 따라 width를 조정하는 방법
2,876
웹서버 ip 확인
2,875
웹호스팅의 절대경로를 확인
2,874
input 입력 필드 앞뒤 공백 실시간 제거
2,873
Placeholder 포커스시 감추기
2,872
MySQL 중복된 데이터를 삭제
2,871
MySQL 중복 데이터 확인
2,870
sessionStorage.getItem 와 sessionStorage.setItem
2,869
제이쿼리 랜덤으로 배경색 변경
2,868
preg match에 관한 정규식
2,867
Stream an audio file with MediaPlayer 오디오 파일 스트리밍 하기
2,866
Audio Streaming PHP Code
2,865
PHP $ SERVER 환경 변수 정리
2,864
Vimeo (비메오) API 를 사용하여 플레이어 컨트롤하기
2,863
iframe 사용시 하단에 발생하는 공백 제거방법
2,862
아이프레임(iframe) 전체화면 가능하게 하기
목록
뮤직트로트 부산광역시 부산진구 가야동 ㅣ 개인정보취급방침ㅣ모바일버전
Copyright ⓒ musictrot All rights reserved.