본문 바로가기

프론트앤드 수업

[php] 파일추가 및 게시판처럼 파일내용 표출하기예제

728x90

글쓰기 선택시 indexwrite.php로 이동하면서 밑에있는 php를 form으로 바꿔준다.
내용 작성후 작성을 입력시 홈으로 돌아간다.
작성완료 ~ 클릭하면 내용이 바뀜

Code

<div id="header">
    <h2>게시판</h2>
    <div>
    <a href="index.php">홈</a>
    <a href="indexwrite.php">글쓰기</a>
    </div>
    </div>
    <div id="content">
    <p>
        <ul>
        <?php
        $lists= scandir('data/');
        for($i=0; $i<count($lists); $i++){
            $title = $lists[$i];
            if($lists[$i] != '.' && $lists[$i] != '..'){
                echo "<li><a href='index.php?title=".$title."'>".$title."</a></li>";
            }
        }
        ?>
        </ul>
    </p>
    <h3>
        <?php
        if(isset($_GET['title'])){
        echo $_GET['title'];
        }
        ?>
    </h3>
    <p>
        <?php
        if(isset($_GET['title'])){
        echo file_get_contents("data/".$_GET['title']);
        }
        ?>
    </p>
</div>
    <div id="footer">
        게시판 만들어보기
    </div>

1. lists 변수에 scandir('data/') 를 입력 data폴더 안에있는 파일들의 제목을 모두 배열로 긁어온다.

2. for문을 이용해 lists의 길이만큼 반복문을 작성한다.

3. title에는 lists[i]의 값을 우선적으로 담아준다.(적기너무힘듬)

4. scandir로 파일을 찾을시 .과 ..이 0번과1번에 담겨있어 그 두개를 제외하기위해 if문을 작성해 lists가 . 이나 .. 이 아닌경우에만 실행시켜준다. 

5. li와 a태그를 넣으면서 태그에 제목을 누를시 그 제목을 get방식으로 받아오기위해 title에 $title를 넣어준다. 그리고 내용을 표츌해놓기 위해 $title를 재입력.

6. <h3>태그안에있는 if(isset($_GET['title']))){

 echo $_GET['title'];

} isset는 값이 안에 들어있는지 확인하는 명령어이다.

isset을 걸어주지않고 echo $_GET['title'] 만 해도 괜찮지만 첫시작에 에러가 발생한다.

입력해주면 처음에 값이 없기래 실행하지않는다.

7. <p>태그안에있는 echo file_get_contents('data/'.$_GET['title']); 파일의 내용을 가져오는 명령어이다. title인 제목을 이용해 data폴더 안에있는 해당 파일의 내용을 가져와 준다.

 

홈버튼 클릭시 기본 index로 이동

글쓰기 버튼 클릭시 indexwrite.php로 이동하는데 나머진 다 같고 p태그에 form을 넣어서 그자리에서 작성이 가능하도록 만들어놓았다.

form 코드부분

 <form action="write.php"  id="a" method="post">
           <input type="text" name='title' required>
           <textarea name="desc" id="desc" cols="30" rows="10" required>

           </textarea>
           <div>
           <button type="submit">작성</button>
           <button type='reset'>취소</button></div>
       </form>

write.php로 데이터를 POST타입으로 넘겨준다.

write.php 코드

   <?php
    $title = $_POST['title'];
    $descc = $_POST['desc'];
    file_put_contents('./data/'.$title,$descc);

    ?>
    <script>
        location.replace('index.php')
    </script>

title와 desc를 받아주고 file_put_contents('./data/'.$title,$descc);  data폴더안에 $title이라는 제목으로 파일을만들고 $descc로 내용을 채운 파일을 만들어준다.

현재 뭔가 이상한지 header명령어가 안되서 script로 우선 처리했다..

728x90
댓글