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);
?>

 

 

 

'php, mysql' 카테고리의 다른 글

외부문서 불러오기 curl  (0) 2017.04.15
정규식 사용하여 자동링크 만들기  (0) 2017.04.14
php 파일 관련 함수 모음 1  (0) 2017.04.13
php 문자열 함수 모음  (0) 2017.04.13
파일저장시 LOCK걸기  (0) 2017.04.13




+ Recent posts