HTML2011. 5. 9. 00:10

basename -- 경로명에서 파일이름만 반환합니다
chgrp -- 파일의 그룹을 변환합니다
chmod -- 파일의 모드 변경
chown -- 파일의 소유자 변경
clearstatcache -- 파일의 통계(stat) 캐시를 삭제합니다.
copy -- 파일을 복사합니다
delete -- 실제로는 없는 명령
dirname -- 경로의 구성요소중에서 디렉토리 이름만 반환합니다.
disk_free_space -- Returns available space in directory
disk_total_space -- Returns the total size of a directory
diskfreespace -- 디렉토리의 사용가능한 공간을 반환합니다.
fclose -- 열려있는 파일 포인터를 닫습니다.
feof -- 파일의 끝이 파일포인터에 있는지 테스트합니다.
fflush -- 출력결과를 파일로 보냅니다.
fgetc -- 파일포인터로부터 문자 가져오기
fgetcsv -- 파일포인터에서 라인을 가져오고 CVS 에 맞게 변환합니다.
fgets -- 파일 포인터에서 라인 가져오기
fgetss -- 파일포인터에서 라인을 가져오고 HTML 태그를 없애기
file_exists -- 파일이 있는지 체크
file_get_contents -- Reads entire file into a string
file_put_contents -- Write a string to a file
file -- 파일전체를 배열로 읽어들임
fileatime -- 최근에 파일에 접근한 시간을 가져옴
filectime -- 파일의 아이노드 변경시간을 가져옵니다
filegroup -- 파일의 그룹을 가져옵니다
fileinode -- 파일의 아이노드를 가져옵니다
filemtime -- 파일이 수정된 시간을 가져옵니다
fileowner -- 파일의 소유자를 가져옵니다
fileperms -- 파일의 권한을 가져옵니다
filesize -- 파일의 크기를 가져옵니다
filetype -- 파일의 형식을 가져옵니다
flock -- 파일 잠김에 관한 간단한 도움말
fnmatch -- Match filename against a pattern
fopen -- 파일이나 URL을 엽니다
fpassthru -- 파일 포인터에 남아있는 모든 데이타를 출력합니다
fputs -- 파일 포인터에 기록하기
fread -- Binary-safe 파일 읽기
fscanf -- 형식에 따라서 파일로 부터 분석하여 입력하기
fseek -- 파일 포인터에서 찾기
fstat -- 오픈 파일 포인터를 사용하는 파일에 대한 정보 가져오기
ftell -- 파일포인터의 읽기/쓰기 위치 말하기
ftruncate -- 주어진 길이로 잘라내기
fwrite -- Binary-safe 파일 쓰기
glob -- Find pathnames matching a pattern
is_dir -- filename 이 디렉토리인지 아닌지 이야기하기
is_executable -- filename이 실행가능한 것인지 아닌지 이야기하기
is_file -- filename이 보통 파일인지 아닌지 이야기하기
is_link -- filename이 심볼릭 링크인지 아닌지 이야기하기
is_readable -- filename이 읽기 가능한 것인지 아닌지 이야기하기
is_uploaded_file -- file이 HTTP POST를 통해 업로드된 것인지 아닌지 이야기하기
is_writable -- filename이 쓰기가능한 것인지 아닌지 이야기하기
is_writeable -- Alias of is_writable()
link -- hard link 만들기
linkinfo -- 링크 정보 가져오기
lstat -- 파일이나 심볼릭 링크에 관한 정보를 제공
mkdir -- 디렉토리 만들기
move_uploaded_file -- 업로드된 파일을 다른곳으로 이동하기
parse_ini_file -- Parse a configuration file
pathinfo -- Returns information about a file path
pclose -- 진행되는 파일 포인터 닫기
popen -- 진행되는 파일 포인터를 열기
readfile -- 파일을 출력합니다
readlink -- symbolic link의 target 반환
realpath -- 표준화된 절대 경로명을 반환합니다
rename -- 파일을 새 이름으로 고치기
rewind -- 파일포인터의 위치를 되돌립니다(rewind).
rmdir -- 디렉토리 제거하기
set_file_buffer -- 주어진 파일 포인터에 파일 버퍼링 설정하기
stat -- file에 대한 정보 제공
symlink -- 심볼릭 링크 만들기
tempnam -- 유일한 파일 이름 만들기
tmpfile -- 임시 파일 만들기
touch -- 파일의 수정시간을 설정합니다
umask -- 현재의 umask를 변경하기
unlink -- 파일을 삭제하기

----예제 포함----------------------------------------------------------------------------------------

fopen() 함수

파일이나 URL을 여는 함수

int fopen(string filename, string mode);


%format 

 

 mode 내 용

'r' 읽기 모드, 파일 포인터는 파일의 처음에 위치

'r+' 읽기/쓰기 모드, 파일 포인터는 파일의 처음에 위치

'w' 쓰기 모드, 파일 포인터는 파일의 처음에 위치

파일이 이미 존재하면 overwrite, 존재하지 않으면 새롭게 생성

'w+' 읽기/쓰기 모드, 파일 포인터는 파일의 처음에 위치

파일이 이미 존재하면 overwrite, 존재하지 않으면 새롭게 생성

'a' 쓰기 모드, 파일 포인터는 파일의 끝에 위치

파일이 이미 존재하면 overwrite, 존재하지 않으면 새롭게 생성

'a+' 읽기/쓰기 모드, 파일 포인터는 파일의 끝에 위치

파일이 이미 존재하면 overwrite, 존재하지 않으면 새롭게 생성


fclose() 함수 

지정된 file pointer에 해당하는 파일이나 URL을 닫는 함수

int fclose(int fp);


fwrite()

인자로 받은 파일 포인터에 지정한 문자열을 기록하는 함수

int fwrite(int fp, string string, int [length]);


fputs()

인자로 받은 파일 포인터에 지정한 문자열을 기록하는 함수

fwrite() 함수와 동일한 기능

int fputs(int fp, string string, int [length]);

 

fread()

인자로 받은 파일 포인터에서 주어진 길이(length - 1 byte)만큼 문자를

binary 형태로 읽어 오는 함수

string fread(int fp, int length);


fgetc() 

인자로 받은 파일 포인터에서 한 문자를 읽어 오는 함수

string fgetc(int fp);


fgets() 

인자로 받은 파일 포인터에서 지정한 길이(length - 1 byte)만큼 문자를

읽어 오는 함수

fread 함수와 달리 개행문자(줄바꿈) 또는 EOF를 만나면 그곳까지만 읽어 오므로

한 라인씩 읽을 때 유용함.


string fgets(int fp [, int length]);

*length 를 생략하면 한 라인을 읽어 옴.

 

filesize()

파일의 크기를 Byte 단위로 반환하는 함수

int filesize(string filename);


filetype()

파일의 타입을 반환하는 함수

int filetype(string filename);


is_dir()

지정된 파일의 타입이 directory이면 true 를 반환하는 함수

bool is_dir(string filename);


is_file()

지정된 파일의 타입이 file이면 true 를 반환하는 함수

bool is_file(string filename);


is_readable() 

지정된 파일에서 읽기가 가능하면 true 를 반환하는 함수

bool is_readable(string filename);


is_writable()

지정된 파일에서 쓰기가 가능하면 true 를 반환하는 함수

bool is_writable(string filename);


is_executable()

지정된 파일이 실행 가능한 파일이면 true 를 반환하는 함수

bool is_executable(string filename);


*상태 캐쉬(state cache) 지우기

상태 정보 관련 함수, 즉, is_file, is_dir, is_readable, ... 등의 함수들을 호출할 때 입력 인자로 파일 이름을 사용하는데, 이 함수들은 다음 호출을 대비하여 시스템의 stat cache에 파일명을 저장하게 됩니다.

이런 자료가 cache에 그대로 남겨 두면 시스템 자원을 낭비하는 것이므로, 마지막 호출 정보를 지워 주는 것이 좋습니다. 이 때 clearstatcache() 함수를 사용하면 됩니다.


파일을 복사하는 함수

copy()

int copy(string source, string dest);

 source : 복사하고자 하는 원본 파일명

 dest : 복사될 파일명 (현 디렉토리가 아니면 디렉토리 경로까지 같이 지정)

 

rename() 

파일의 이름을 변경하는 함수

int rename(string oldname, string newname);

 

unlink() 

파일을 삭제하는 함수

int unlink(string filename);


*rename, unlink 함수를 사용하기 위해서는 파일에 대한 Permission이 있어야 함.

 

chdir()

directory를 바꾸는 함수

int chdir(string pathname);

pathname : 디렉토리 경로


mkdir() 

directory를 생성하는 함수

int mkdir(string pathname, int mode);

mode : Permission

*rmdir 함수를 사용하기 위해서도 Permission이 있어야 함 


rmdir()

directory를 삭제하는 함수

int rmdir(string dirname);     directory handle을 닫는 함수

int opendir(int directory_handle);


opendir()

directory handle을 여는 함수

int opendir(string pathname);


readdir()

directory handle로부터 항목

(디렉토리,파일)을 읽어오는 함수

int readdir(int directory_handle);


include()

지정된 파일을 읽어 실행하는 함수

include(filename);


require()

지정된 파일을 읽어 실행하는 함수

include 함수와 달리 자신을 지정된 파일로 대체함. 반복문에서 사용할 수 없다.

require(filename); 


readfile($filename) include, require 함수와 같은 기능

->복잡한 index.html의 update를 간편하게 하는데 사용


파일의 업로드(client->server) 순서

1.먼저 클라이언트가 form tag을 이용하여 전송.

  <input type=file name=upfile>

2.서버는 이를 받아서 임시디렉토리에 저장.

$upfile 업로드된 파일이 임시 디렉토리에 저장될 때 가지는 임시 파일명-리눅스,유닉스에서 확인해 보자.

파일명,크기,타입의 원래 유형을 알고 싶을 때 사용하는 방법

$upfile_name 업로드될 때의 실제 파일명

$upfile size 업로드된 파일의 크기(Byte)

$upfile_type  업로드된 파일의 MIME 타입


1.Upload form 만들기 유의사항

ENCTYPE : file upload 시 지정해야 하는 MIME TYPE

                    반드시 multipart/form-data라 해야 함.

 method : 반드시 POST 방식으로 보내야 함.



<h3>파일 열고 닫기</h3>       

<hr>   

<?php  

    $fp = fopen("readme.txt","r"); 

    if(!$fp) echo "파일 열기 실패<br>";  

    else { echo "파일 열기 성공<br>";   

           fclose($fp); } 

    $fp = fopen("readme.txt","a+");       

    if(!$fp) echo "파일 열기 실패<br>";  

    else { echo "파일 열기 성공<br>";   

           fclose($fp); } 

?>     


<h3>파일에 기록하기</h3>      

<hr>   

<?php  

     $date = date("Y/m/d h:i");  

        

     $fp = fopen("logfile.html","a");      

     $str = "<li>접속일시 = $date";     

     $str .= "<li>접속 IP = $REMOTE_ADDR";  

     fwrite($fp,$str);    

         //fputs($fp,$str); 도 동일한 결과 

     fclose($fp); 

        

     echo "<a href=logfile.html>Logfile</a>";    

?>


<h3>파일에서 읽어 오기</h3>   

<hr>   

<?php  

     $fp = fopen("http://www.yahoo.com","r");    

     $content = fgets($fp,4096); 

     echo $content;     

     fclose($fp);        

     echo "<br><br>"; 

     $fp = fopen("http://www.yahoo.com","r");    

     $content = fread($fp,4096); 

     echo $content;     

     fclose($fp); 

?>     

<h3>파일의 크기/타입 구하기</h3>      

<hr>   

<?php  

     $filename = "logfile.html";  

     $file_size = filesize($filename);      

     $file_type = filetype($filename);     

     echo "Logfile 크기 : $file_size Byte <br>";  

     echo "Logfile 타입 : $file_type <br>";       

        

     //해당 디렉토리에 존재하지 않으면 반드시 디렉토리명까지 지정한다   

     $file_size = filesize("./tmp/".$filename);      

     $file_type = filetype("./tmp/".$filename);     

     echo "Logfile 크기 : $file_size Byte <br>";  

     echo "Logfile 타입 : $file_type <br>";       

?>     

<h3>파일의 상태 확인하기</h3> 

<hr>   

<?php  

     $filename = "readme.txt";   

     if (is_file($filename)) {     

         echo "$filename 파일이 존재합니다.<br>";       

         if (is_readable($filename))      

             echo "$filename 파일은 읽기 가능합니다.<br>";      

         else   

             echo "$filename 파일은 읽을 수 없습니다.<br>";     

     }  

     else       

         echo "$filename 파일이 존재하지 않습니다.<br>"; 

        

     clearstatcache();    

?>     

<h3>파일 복사/삭제하기</h3>   

<hr>   

<?php  

     $filename = "readme.txt";   

     if (is_file($filename)) {     

         if (copy($filename, "b.txt")) {   

             echo "$filename 파일을 복사하였습니다.<br>";       

             $filename = "b.txt"; 

             if (unlink($filename))       

                echo "$filename 파일을 삭제하였습니다.<br>";    

             else       

                echo "$filename 파일 삭제에 실패하였습니다.<br>";       

         }      

         else   

             echo "$filename 파일 복사에 실패하였습니다.<br>";  

     }  

     else       

         echo "$filename 파일이 존재하지 않습니다.<br>"; 

?>     

<h3>디렉토리 관리하기</h3>    

<hr>   

<?php  

    $dirname = "test";  

    if (mkdir('./'.$dirname, 0777)) {      

         echo "$dirname 디렉토리를 생성하였습니다.<br>";       

         if (chdir('test')) {      

             $filename = "readme.txt";   

             if (copy('../'.$filename, 'c.txt'))     

                 echo "$filename 파일을 복사하였습니다.<br>";   

             else       

                 echo "파일 복사에 실패하였습니다.";     

         }      

         else   

             echo "디렉토리 변경에 실패하였습니다.";     

    }   

    else 

         echo "디렉토리 생성에 실패하였습니다."; 

?>     


dirlist.php

<?php

    if (!$dir) {

      $dir = "/usr/local/apache/htdocs/file";

    }


    chdir($dir);

    $dp = opendir($dir);


    echo "<center>";

    echo "<h3>파일 업로드 예제</h3>";

    echo "<table><tr><td>";

   

    //디렉토리 생성 폼

    echo "<form action=mkdir.php>

           <input type=hidden name=dir value=$dir>

           <input name=new_dir>

           <input type=submit value=디렉토리생성>

          </form>"; 


   //파일 업로드 폼

  echo "<form method=POST  ENCTYPE=multipart/form-data  action=upload.php?dir=$dir>

        <input type=file name=userfile>

        <input type=submit value=업로드>

        </form>";      

          

   echo "<a href=mkfileform.php?dir=$dir>

                파일 직접 작성

         </a><p>";


    echo "<table cellspacing=1 border=1>

          <tr>

          <th>파일이름

          <th>크기(Bytes)

          <th>수정일

          <th>타입

          <th>삭제

          </tr>";


    while($filename = readdir($dp)){

        if(is_dir($filename)) {

            $img = "<img src=dir.gif width=15>";

        } else {

            $img = "<img src=text.gif width=15>";

        }


        $filesize = filesize($filename);

        $filedate = date("Y/m/d h:i",filemtime($filename));

        $filetype = filetype($filename);

        

      if(substr($filename,0,1)!="."){

        echo "<tr>";


        if(is_dir($filename)) {

           echo "<td>$img <a href=dirlist.php?dir=$dir/$filename>$filename</a>";

        } else {         

            echo "<td>$img $filename";

        }

        

        echo "<td align=center>$filesize

            <td align=center>$filedate

            <td align=center>$filetype

            <td align=center><a href=delete.php?dir=$dir&file=$filename>삭제</a>

            </tr>";

    } }

    

    echo "</table>";

    

    echo "</td></tr></table>";

    echo "</center>";

    closedir($dp);

?>


mkdir.php

<?php

    $res = mkdir($dir."/".$new_dir,0777) ;

    if(!$res) {

        echo "디렉토리 생성 실패";

        exit;

    }

   

    echo "디렉토리 생성 성공

           <meta http-equiv=refresh content=1;url=dirlist.php?dir=$dir>";

?>


upload.php

<?php

    echo "<li>실제 파일내용 : $userfile

          <li>업로드시 파일 이름 : $userfile_name

          <li>파일 크기 : $userfile_size Byte

          <li>파일 타입 : $userfile_type";


    $result = copy($userfile,$dir."/".$userfile_name) ;       

    if(!$result) {

        echo "파일 업로드 실패";

        exit;

    }


    echo "<meta http-equiv=refresh content=1;url=dirlist.php?dir=$dir>";

?>     


mkfile.php

<?php

     $fp = fopen($dir."/".$filename,"w");

     fwrite($fp,$content);

     fclose($fp);

     echo "<meta http-equiv=refresh content=1;url=dirlist.php?dir=$dir>";

?>


mkfileform.php

    <form action=mkfile.php?dir=<? echo $dir ?> method=POST>

    <table cellspacing=1>

    <tr>

    <th>파일 이름

    <td><input name=filename>

    </tr>

    <tr>

    <th>파일 내용

    <td><textarea name=content cols=40 rows=10>

        </textarea>

    </tr>

    <tr>

    <th colspan=2><input type=submit value=파일작성>

    </tr>

    </table>

    </form>


delete.php

<?php

    $res = unlink($dir."/".$filename) ;

    if(!$res) {

        echo "파일 삭제 실패";

        exit;

    }

   

    echo "파일 삭제 성공

           <meta http-equiv=refresh content=1;url=dirlist.php?dir=$dir>";

?>


opendir.php

<?

    $dir = "/open/comliving/adver/log";

    chdir($dir);

    $dp = opendir($dir);

    while($filename = readdir($dp)){

       echo "항목=>".$filename."<br>";

    }

    closedir($dp);

?>


Posted by 아이맥스