PHP 특정 폴더 내에 있는 파일들을 선택적으로 삭제 하고자 할 때
웹프로그램다음과 같은 함수를 할용하시면 됩니다.
1. opendir(path)
path 지정한 경로의 폴더안에 있는 파일들을 불러 옵니다.
예)
<?php
$dir = "/etc/php5";
// 알고 있는 디렉토리를 열어서, 내용을 읽어들이는 작업입니다.
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
결과)$dir = "/etc/php5";
// 알고 있는 디렉토리를 열어서, 내용을 읽어들이는 작업입니다.
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
}
closedir($dh);
}
}
?>
filename: . : filetype: dir
filename: .. : filetype: dir
filename: apache : filetype: dir
filename: cgi : filetype: dir
filename: cli : filetype: dir
2. glob(패턴)
파일의 패턴을 호출할때 사용합니다. 예로 *.txt 라고 하면 txt 확장자 파일을 모두 찾아 줍니다.
예)
<?php
foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
결과)foreach (glob("*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "\n";
}
?>
funclist.txt size 44686
funcsummary.txt size 267625
quickref.txt size 137820
3. unlink(파일)
지정한 파일 및 폴더를 삭제 합니다. 위 함수를 이용해서 찾은 파일을 삭제하고자 할때 이용합니다.
예)
<?php
$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);
mkdir('testdir', 0777);
unlink('test.html');
unlink('testdir');
?>
결과) 지정한 파일 삭제$fh = fopen('test.html', 'a');
fwrite($fh, '<h1>Hello world!</h1>');
fclose($fh);
mkdir('testdir', 0777);
unlink('test.html');
unlink('testdir');
?>
삭제할 파일의 폴더에 지울수 있는 권한이 있어야 합니다.
댓글을 달아 주세요