생활코딩

Coding Everybody

코스 전체목록

닫기

파일의 제어

파일 다루기

파일복사

/file/7.php

<?php
$file = 'readme.txt';
$newfile = 'example.txt.bak';

if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>

파일삭제

<?php
unlink('deleteme.txt');
?>

읽고 쓰기

 

file_get_contents

1.php

1.php 파일과 같은 디렉토리에 readme.txt 파일이 존재해야 한다.
<?php
$file = './readme.txt';
echo file_get_contents($file);
?>

file_put_contents

2.php

<?php
$file = './writeme.txt';
file_put_contents($file, 'coding everybody');
?>
좀 더 고급스러운 파일 제어를 원한다면 fopen을 참조하자.

네트웍크를 통해서 데이터 읽어오기

<?php
$homepage = file_get_contents('http://php.net/manual/en/function.file-get-contents.php');
echo $homepage;
?>

파일을 다루는 과정에서 발생할 수 있는 문제들

권한

파일을 읽고 쓸 때 권한의 문제로 오류가 발생할 수 있다. 권한에 대한 문제는 다소 복잡하기 때문에 동영상 강의를 참고한다.

아래 코드는 특정 파일이 읽을 수 있는 상태인지를 확인한다.

/file/4.php

<?php
$filename = 'readme.txt';
if (is_readable($filename)) {
    echo 'The file is readable';
} else {
    echo 'The file is not readable';
}
?>

다음 코드는 특정 파일이 쓰기가 가능한지 확인한다.

/file/5.php

<?php
$filename = 'writeme.txt';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'The file is not writable';
}
?>

아래는 파일의 존재 여부를 확인한다.

/file/6.php

<?php
$filename = 'readme.txt';
if (file_exists($filename)) {
    echo "The file $filename exists";
} else {
  	echo "The file $filename is not exists";
}
?>

참고

file_get_contents, file_put_content를 사용할 수 없는 경우라면 fread, fwrite 함수를 사용해야 한다. 자세한 내용은 다음 링크를 참고한다. 

댓글

댓글 본문
버전 관리
egoing
현재 버전
선택 버전
graphittie 자세히 보기