Linux WebServer Directory List 출력(with php)

|


1. 제작 동기


java 수업의 강사님께서는 hfs라는 프로그램을 이용하여 WebFileServer를 구축하셔서 파일을 공유하셨다.

해당 프로그램의 모든 기능을 구현하기란 아직 내 실력으로 힘들겠지만

디렉터리 이동 및 개별파일 다운로드 기능 구현은 할만하다고 생각되어 도전해보았고 어느정도 구현하였다.



2. 구현 환경


리눅스 가상머신을 설치하여 Apache, php가 설치된 리눅스 웹서버에서 동작하는 환경을 구축하였다.

(내가 구축한 소스는 리눅스 웹서버에서만 동작한다.)


1) Apache 설정


기존 /var/www/html 에는 구동중인 웹서버가 있기 때문에 다른 공간이 필요했다.

그래서 선택한 것은 Apache에서 제공하는 UserDir 기능이다.

UserDir기능은 http://Serverip/~Username 의 경로에 각 사용자별 웹서버를 띄우는 기능이다.


# vi /etc/httpd/conf/httpd.com

    # 특정 사용자만 UserDir 사용하도록 설정

    366     UserDir disabled
    367     UserDir enabled username


    # 사용자 홈 디렉터리 밑에 사용할 Web Root Directory

    374     UserDir public_html


    # /home/*/public_html 에 적용되는 Apache세부 설정

    382 <Directory /home/*/public_html>

          ...

          # Options 에서 Indexes를 설정하면 내가 구현한 정도의 기능은 자동으로 구현된다.
    384     Options -Indexes

    # index.php가 아닌 숨김파일을 index page로 설정
    385     DirectoryIndex .....list.php

          ...

    # 다른 기타 설정은 개인의 취향에 맞게 설정
    394 </Directory>



httpd 재시작

# service httpd restart



2) 사용자 홈 디렉터리 설정


사용자 홈 디렉터리에 웹 루트 디렉터리 생성 및 외부에서 접근 가능하도록 권한 설정

# cd ~username

# mkdir public_html/

# chmod o+x public_html/



3) 개발 툴


Editplus를 사용하였으며, FTP 설정을 해주면 실시간으로 업로드하여 결과를 확인할 수 있다.

구지 FTP를 연동하여 실시간 업로드를 설정한 이유는 리눅스에 명령어를 입력하여 파싱해왔기 때문이다.




3. 구현 코드


문법적 오류가 다분한 영어로 주석을 달아놓았다.

(다운로드하여 리눅스 웹서버에 올려놓고 직접 확인하면서 보면 좋을것 같다.

.....list.php



<!--
 @ Copyright : Jiwoong Jung
 @ E-mail : kanziwoong@gmail.com
-->
<?php
 // For Index where title and body
 // 1. Execute "pwd" command and Get result to $pwdExecc
 // 2. Explode $pwdExecc with "/" and Save result to $curPathArr
 // 3. In Linux Server, web root directory is located in /home/$USERNAME/public_html/
 //    So conceal "/home/$USER/public_html" through rearrangement to $curPathArr.
 $curPathArr = explode("/", exec("pwd", $pwdExecc, $er));
 $curPath = "/";
 for ($i=0;$i<count($curPathArr)-4 ;$i++ ) {
    $curPath = "$curPath".$curPathArr[$i+4]."/";
  }
?>
<html>
 <head>
  <title>Index of <?php echo "$curPath"; ?></title>
  <!-- CSS from http://ftp.kaist.ac.kr/CentOS/ -->
  <style type="text/css">
   a, a:active {text-decoration: none; color: blue;}
   a:visited {color: #48468F;}
   a:hover, a:focus {text-decoration: underline; color: red;}
   body {background-color: #F5F5F5;}
   h2 {margin-bottom: 12px;}
   table {margin-left: 12px;}
   th, td {font: 90% monospace; text-align: left;}
   th {font-weight: bold; padding-right: 14px; padding-bottom: 3px;}
   td {padding-right: 14px;}
   td.s, th.s {text-align: right;}
   div.list {background-color: white; border-top: 1px solid #646464; border-bottom: 1px solid #646464; padding-top: 10px; padding-bottom: 14px;}
   div.foot {font: 90% monospace; color: #787878; padding-top: 4px;}
  </style>
 </head>

 <body>
  <h2>Index of <?php echo "$curPath"; ?></h2>
  <div class="list">
   <table summary="Directory Listing" cellpadding="0" cellspacing="0">
    <thead><tr><th class="n">Name</th><th class="m">Last Modified</th><th class="s">Size</th><th class="t">Type</th></tr></thead>
    <tbody>
<?php
 // If $cupPath != "/", print Parent Directory Link
 if ($curPath!="/"){
?>
     <tr>
      <td class="n"><a href="../">Parent Directory/</a></td>
      <td class="m"></td>
      <td class="s">-</td>
      <td class="t">Directory</td>
     </tr>
<?php
 }
?>
     <tr>
<?php

 // For save parameter for print table
 // 1. Execute "ls -l" command and Get result to $output
 exec("ls -l ./", $output, $error);
 // 2. Seperate $output per line to $val
  while(list($key, $val) = each($output)) {
 // 3. ls -l command prints "total Size", so except this.
   if ($key!=0) {
 // 4. Seperate $val by space and save this to $rst
    $rst = explode(" ", $val);
 // 5. Some $rst array has NULL value, so rearray to rstTrue
    $j=0;
    for ( $i=0 ; $i<count($rst) ; $i++)
    {
     if ($rst[$i]){
      $rstTrue[$j]=$rst[$i];
      $j++;
     }
    }
 // 6. Mark FILENAME, SIZE and DATE parameter
    $FILENAME = $rstTrue[8];
    $SIZE = $rstTrue[4];
    $DATE = "$rstTrue[5]"." $rstTrue[6]"." $rstTrue[7]";
 // 7. Mark Directory PROPERTY parameter
    if (substr($rstTrue[0], 1)=="d"){
     $PROPERTY = "Directory";
    }

 // 8. Mark Application PROPERTY parameter
    else if (substr($rstTrue[0], 4, 1)=="x" || substr($rstTrue[0], 7, 1)=="x" || substr($rstTrue[0], -1)=="x"){
     $PROPERTY = "application";
 // 9. Mark Additional Application PROPERTY parameter
     if (substr($rstTrue[0], -6)=="tar.gz")
      $PROPERTY = "$PROPERTY"."/tar.gz";
     }
 // 10. with else if, we can set more PROPERTY parameter
    else $PROPERTY = "text/plain";
?>
      <td class="n"><a href="./<?php echo "$FILENAME" ?>"><?php echo "$FILENAME" ?></a></td>
      <td class="m"><?php echo "$DATE" ?></td>
      <td class="s"><?php echo "$SIZE" ?></td>
      <td class="t"><?php echo "$PROPERTY" ?></td>
     </tr>
<?php
   
  }
 }
?>
    </tbody>
   </table>
  </div>
  <div class="foot">Copyright Jiwoong Jung</div>
 </body>
</html>




4. 단점 및 추가/개선해야할 점


가장 큰 단점은 .....list.php 파일을 생성되는 모든 디렉터리 안에 넣어줘야 한다는 것이다.

디렉터리가 생성 될 떄마다 위 파일을 넣어주는 것이 여간 귀찮은 일이 아닐 것이다.

또한 이 코드는 Linux환경에서만 유효하다.

나는 CentOS6.6 인데 다른 배포판, 혹은 다른 버젼은 안될 수도 있다.

하지만 리눅스 환경이라면 코드를 조금만 수정 하면바로 적용 가능할 것이다.


가능하다고 생각되어 지는 추가 기능으로는 버튼을 눌렀을 때 디렉터리 째로 압축되는 기능이다.

하지만 .....list.php의 존재 때문에 모든 하위디렉터리까지는 힘들것 같다.

혹 .....list.php를 모든 디렉터리에 넣어야 하는 단점이 극복된다면 하위디렉터리까지도 압축 가능하다.


개선해야할 점으론 디렉터리 링크 클릭 시에는 디렉터리간 이동이,

비 디렉터리 파일 클릭 시에는 파일 다운로드가 진행되어야 하는데 html, php 등의 파일이 업로드 되어있으면 다운로드가 되지 않는다.

<a> 태그에 download를 기입하면 다운로드 창이 뜬다고는 하는데 알 수 없는 이유로 구현 실패했다.

Directory가 아니면 download를 <a>태그에 추가하는 기능이었는데 구현 실패했다.




'Language > PHP' 카테고리의 다른 글

<?php ?> 와 <? ?> 차이  (0) 2015.10.05
And