훈, IT 공부/Html,CSS,PHP

PHP, php를 이용한 파일 다루기

IT훈이 2018. 8. 28.
반응형

php 파일 관련

Copy()
함수원형
bool copy ( string $source , string $dest [, resource $context ] )

1
2
3
4
5
6
7
8
<?php
$file = 'example.txt';
$newfile = 'example.txt.bak';
 
if (!copy($file$newfile)) {
    echo "failed to copy $file...\n";
}
?>
cs

- 특정 대상 파일을 복사할때 사용한다.


Unlink()

함수원형

bool unlink ( string $filename [, resource $context ] )


1
2
3
4
5
6
7
<?php
$fh = fopen('test.html''a');
fwrite($fh'<h1>Hello world!</h1>');
fclose($fh);
 
unlink('test.html');
?>
cs

- 특정 파일을 삭제할때 사용한다.




파일 읽고 쓰기


▶ file_get_contents()

함수원형

string file_get_contents ( string $filename [, bool $use_include_path = FALSE[, resource $context [, int $offset = 0 [, int $maxlen ]]]] )


ex1)
1
2
3
4
5
6
<?php
$homepage = 'http://www.google.com/';
 
$return_page = file_get_contents($homepage);
echo $return_page;
?>
cs

- 텍스트로 만들어진 파일을 읽을때 사용된다.


file_put_contents()

함수원형

int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context]] )


ex1)

1
2
3
4
5
6
7
8
9
<?php
$file = 'people.txt';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= "John Smith\n";
// Write the contents back to the file
file_put_contents($file$current);
?>
cs

ex2)
1
2
3
4
<?php
$file = './writeme.txt';
file_put_contents($file'coding everybody');
?>
cs

- 파일을 쓸때 사용된다.

- $current 파일내용을 $file 에게 전달한다.

- 코드에서는 people.txt 파일 내용에 'John Smith\n'를 추가하여 변수에 넣겠다는 것이다.



구글에 검색어 'php file function' 검색하면 파일 관련 함수 검색이 가능하다는 것.




생활코딩 참고

반응형

'훈, IT 공부 > Html,CSS,PHP' 카테고리의 다른 글

PHP. php를 이용한 폴더 다루기  (0) 2018.08.31

댓글