본문 바로가기
PHP

[PHP] 파일 제어

by 헤이봄봄 2022. 6. 15.

파일 복사

copy라는 함수를 호출하여

첫번째 인자엔 원본파일의 이름이, 두번째 인자엔 원본파일을 복사한 파일의 이름이 위치해야함

카피가 성공하면 true, 실패하면 false

<?php
$file = 'readme.txt';           #원본파일
$newfile = 'example.txt.bak';   #원본파일이 copy될 파일

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

 

▼ copy 성공 

 

파일 삭제

unlink 함수사용

<?php
    unlink('example.txt.bak');
?>

 

▼ delete 성공 

 

파일 읽기, 쓰기

file_get_contents 함수사용

기존에 있던 파일을 읽는것 

텍스트로 이루어진 파일을 읽어서 문자열을 리턴 

<?php
    $file = './readme.txt';
    echo file_get_contents($file);
?>


// 네트워크를 통해 데이터 읽어오기도 가능하다 
<?php
    $homepage = file_get_contents('http://php.net/manual/en/function.file-get-contents.php');
    echo $homepage;
?>

 

file_put_contents 함수사용 

어떤 파일을 만들어서 어떠한 데이터를 기록하는것 

<?php
    $file = './writeme.txt';
    file_put_contents($file, 'coding everybody!!!');
?>

writeme.txt 파일이 만들어지고 'coding everybody!!!' 텍스트가 삽입된다. 

 

fopen 함수

파일을 열어서 쓰거나 읽거나 하는 또 다른 함수 

https://www.php.net/manual/en/function.fopen

 

PHP: fopen - Manual

The verbal descriptions take a while to read through to get a feel for the expected results for fopen modes. This csv table can help break it down for quicker understanding to find which mode you are looking for:Mode,Creates,Reads,Writes,Pointer Starts,Tru

www.php.net

 

 

파일을 읽고쓸때 권한 문제로 오류가 발생하는 경우가 종종 있음

is_readable 함수로 파일을 읽을 수 있는지 확인

is_writable 함수로 파일에 쓰기가 가능한지 확인

file_exists 파일이 있는지 없는지 확인 

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

'PHP' 카테고리의 다른 글

[PHP] 파일 업로드  (0) 2022.06.16
[PHP] 디렉토리 제어  (0) 2022.06.15
[PHP] include와 namespace  (0) 2022.06.14
[PHP] 배열  (0) 2022.06.14
[PHP] 반복문 if문 while문 break, continue  (0) 2022.06.14

댓글