ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2023_09_03 MySQL&PHP 공부정리
    개발공부/MySQL 2023. 9. 4. 00:18

    https://www.youtube.com/watch?v=wlZ8PE8yddE&list=PLuHgQVnccGMA5836CvWfieEQy0T0ov6Jh&index=18 

    [생활코딩] 10.3강 ~

     

    <배운것>

    -XXS 기법 : DB에 <script></script>태그를 이용해서 js코드를 이용해 공격하는방법

    이는 사용자에게 출력되는 정보들을 htmlspecialchars();함수로 방어가능하다. 이는 꺽쇠들을 &lt; &gt;로 변경하는 함수이다.

    while ($row = mysqli_fetch_array($result)){
        $escaped_title = htmlspecialchars($row['title']);  //사용자에게 보여지는 title을 htmlspecialchars()함수로 처리.
        $list = $list."<li><a href=\"index.php?id={$row['id']}\">{$escaped_title}</a></li>";   
    }
    if (isset($_GET['id'])){
        $filtered_id = mysqli_real_escape_string($conn, $_GET['id']);
        $sql = "SELECT * FROM topic WHERE id={$filtered_id} LIMIT 100";
        $result = mysqli_query($conn, $sql);
        $row = mysqli_fetch_array($result);
        $article = array(
            'title'=>htmlspecialchars($row['title']),
            'description'=>htmlspecialchars($row['description'])   //사용자에게 보여지는 title과 description을 escaping함.
        );
    }

     

    -update.php의 form태그 코드리뷰

        <form action="process_update.php" method="POST">
            <input type="hidden" name="id" value="<?=$_GET['id']?>">   //id를 전송해야 수정할 row를 지정할 수 있음.
            <p><input type="text" name="title" placeholder="title" value='<?=$article['title']?>'></p>
            <p><textarea name="description" placeholder="description"><?=$article['description']?></textarea></p>
            <p><input type="submit"></p> //각각 수정될 내용을 미리 input에 넣어놓음
        </form>    

    -process_update.php 코드리뷰

    <?php
    $conn = mysqli_connect("localhost:81", "root", "password", "opentutorials2");

    settype($_POST['id'], "integer"); //settype(값, 자료형)하면 값이 자료형으로 변환됨. 여기서는 id값을 정수로 바꿈.
    $filtered = array(
        'id'=>mysqli_real_escape_string($conn, $_POST['id']),
        'title'=>mysqli_real_escape_string($conn, $_POST['title']),
        'description'=>mysqli_real_escape_string($conn, $_POST['description'])
    );
    $sql = "UPDATE topic
            SET
            title='{$filtered['title']}',
            description='{$filtered['description']}',
            created=NOW()
            WHERE id = {$filtered['id']};
    ";
    $result = mysqli_query($conn, $sql);
    if($result == false){
        echo "저장하는 과정에서 문제가 생겼읍니다.";
        error_log(mysqli_error($conn));
    } else {
        echo "성공했읍니다. <a href='index.php'>돌아가기</a>";
    }
    ?>

    -index.php의 delete 링크 코드리뷰

    delete는 get방식으로 전달하면 링크를 주소창에 입력하면 삭제가 일어날수 있으므로 POST방식으로 만들어야함

        $delete_link = '
            <form action="process_delete.php" method="POST">   //post방식 전달하는 form태그 형성. a태그로 X
                <input type="hidden" name="id" value="'.$_GET['id'].'"> //id값을 주소창에서 가져옴
                <input type="submit" value="delete">
            </form>
        ';  

    -process_delete.php 코드리뷰

    <?php
    $conn = mysqli_connect("localhost:81", "root", "password", "opentutorials2");

    settype($_POST['id'], "integer");
    $filtered = array(
        'id'=>mysqli_real_escape_string($conn, $_POST['id'])
    );
    $sql = "DELETE FROM topic
            WHERE id = {$filtered['id']};   //행전체를 삭제할것이기 때문에 title이나 description에 관한 정보를 받지않았음.
    ";
    $result = mysqli_query($conn, $sql);
    if($result == false){
        echo "삭제하는 과정에서 문제가 생겼읍니다.";
        error_log(mysqli_error($conn));
    } else {
        echo "삭제했습니다. <a href='index.php'>돌아가기</a>";
    }
    ?>

     

    -ALTER TABLE 테이블명 ADD COLUMN 필드명 필드타입 : 테이블에 새로운 필드를 추가하는 명령

    ex)ALTER TABLE topic ADD COLUMN author_id INT(11); : topic테이블에 author_id라는 필드를 추가.

     

    -<select>태그. 선택이 가능한 상자를 만듬.

    ex)

    <select>

      <option>option1</option>

      <option>option2</option>

      <option>option3</option>

    </select>

     

    -create.php <select>태그를 이용한 author선택하기 코드리뷰

    $sql = "SELECT * FROM author";   //sql문작성
    $result = mysqli_query($conn, $sql);  //sql문 전송
    $select_form = '<select name="author_id">';  //select태그를 만드는 준비. 아래에 select태그를 닫는 코드가 포함되어있음
    while($row = mysqli_fetch_array($result)){
        $select_form .= '<option value="'.$row['id'].'">'.$row['name'].'</option>';  
     //<option>태그를 이용해 select상자에 들어가는 값들을 반복문을 통해 작성
    }
    $select_form .= '</select>'; //$select_form = $select_form.'</select>';와 같은의미
    ?>

     

    -<table>태그. : 예시와 같이 tr태그를 먼저 크게 열고, <td>태그로 각 열을 구성함.

    1행씩 적을때 무조건 <tr>태그로 열고닫아야함

    <table border="1"> //border속성 지정가능
      <tr>  //맨처음 tr태그를 크게 열음
        <td>id</td><td>name</td><td>profile</td>     //필드값
        <tr> 
            <td>1</td><td>egoing</td><td>developer</td>  //1행값
        </tr> //각행마다 tr태그로 열고닫음
        <tr>
            <td>2</td><td>duru</td><td>DBA</td> //2행값
        </tr>
        <tr>
            <td>3</td><td>leecheze</td><td>desinger</td>  //3행값
        </tr>
      </tr> //처음 tr태그를 닫는 태그
    </table>

    <table>태그로 만든 표

    -author.php(18강-create) 코드리뷰

        <table border="1">
            <tr>
                <td>id</td><td>name</td><td>profile</td>
                <?php
                $sql = "SELECT * FROM author";
                $result = mysqli_query($conn, $sql);
                while ($row=mysqli_fetch_array($result)){
                    $filtered = array(
                        'id'=>htmlspecialchars($row['id']), 
                        'name'=>htmlspecialchars($row['name']),
                        'profile'=>htmlspecialchars($row['profile'])    
                    )
    //사용자에게 보여지는 데이터이기 때문에 xxs공격가능. 따라서 htmlspecialchars를 통해 꺽쇠들을 무효화시킴.
                    ?>
                    <tr>
                        <td><?=$filtered['id']?></td>
                        <td><?=$filtered['name']?></td>
                        <td><?=$filtered['profile']?></td>
                    </tr>
                    <?php
                }
                ?>
            </tr>
        </table>
    <form action="process_create_author.php" method="POST">
            <p><input type="text" name="name" placeholder="name"></p>
            <p><textarea name="profile" placeholder="profile"></textarea></p>
            <p><input type="submit" value="Create author"></p>
    </form> //새로운 author를 추가할 form을 만든것.

    -process_create_author.php 코드리뷰

    <?php
    $conn = mysqli_connect("localhost:81", "root", "mysql", "opentutorials2");
    $filtered = array(
        'name'=>mysqli_real_escape_string($conn, $_POST['name']),
        'profile'=>mysqli_real_escape_string($conn, $_POST['profile']),
    );
    $sql = "INSERT INTO author
            (name, profile)
            VALUES(
            '{$filtered['name']}',
            '{$filtered['profile']}'
            );
    ";
    $result = mysqli_query($conn, $sql);
    if($result == false){
        echo "저장하는 과정에서 문제가 생겼읍니다.";
        error_log(mysqli_error($conn));  
    } else {
        header('Location: author.php'); //작성된 후 author.php로 리다이렉션되게 하는 코드
    }
    ?>

     

    -author.php(19강-update) 코드리뷰

    <table border="1">
            <tr>
                <td>id</td><td>name</td><td>profile</td><td></td> //update링크를 위해 td태그 하나더 생성
                <?php
                $sql = "SELECT * FROM author";
                $result = mysqli_query($conn, $sql);
                while ($row=mysqli_fetch_array($result)){
                    $filtered = array(
                        'id'=>htmlspecialchars($row['id']),
                        'name'=>htmlspecialchars($row['name']),
                        'profile'=>htmlspecialchars($row['profile'])
                    )
                    ?>
                    <tr>
                        <td><?=$filtered['id']?></td>
                        <td><?=$filtered['name']?></td>
                        <td><?=$filtered['profile']?></td>
                        <td><a href="author.php?id=<?=$filtered['id']?>">update</td> //update링크를 생성
                    </tr>
                    <?php
                }
                ?>
            </tr>
        </table>
        <?php
        $escaped = array(
            'name' => "",
            'profile' => ""
        );  //id 파라미터가 없는경우 name과 profile에 공백
        $label_submit = 'Create author';  //id 파라미터가 없는경우 submit의 value값은 create author
        $form_action = 'process_create_author.php'; //iid 파라미터가 없는경우 form의 action은 process_create_author.php로
        $form_id = ''; //id 파라미터가 없는경우 전달할 id값이 없음
        if (isset($_GET['id'])){ //id값이 있는 경우
            $filtered_id = mysqli_real_escape_string($conn, $_GET['id']); //id값으로 sql injection이 가능하므로 filtering 한 코드
            settype($filtered_id, "integer"); //id를 정수타입으로 바꾼 코드
            $sql = "SELECT * FROM author WHERE id={$filtered_id}"
            $result=mysqli_query($conn, $sql);
            $row=mysqli_fetch_array($result);
            $escaped['name'] = htmlspecialchars($row['name']); //사용자에게 출력될 값을 escaping하여 xxs공격 방지
            $escaped['profile'] = htmlspecialchars($row['profile']);
            $label_submit = "Update author"; //id 파라미터가 있는경우 submit제출버튼 value를 바꿈
            $form_action = 'process_update_author.php'; //id 파라미터가 있는경우 form action을 process_update_author로
            $form_id = '<input type="hidden" name="id" value="'.$_GET['id'].'">';
    //id 파라미터가 있는경우 id값을 같이 전송하도록 hidden input박스를 생성
        }
        ?>
        <form action="<?=$form_action?>" method="POST">
                <?=$form_id?>
                <p><input type="text" name="name" placeholder="name" value="<?=$escaped['name']?>"></p>
                <p><textarea name="profile" placeholder="profile"><?=$escaped['profile']?></textarea></p>
                <p><input type="submit" value="<?=$label_submit?>"></p>
        </form>
    </body>
    </html>

    -process_update_author.php 코드리뷰

    <?php
    $conn = mysqli_connect("localhost:81", "root", "password", "opentutorials2");
    $filtered = array(
        'id'=>mysqli_real_escape_string($conn, $_POST['id']),
        'name'=>mysqli_real_escape_string($conn, $_POST['name']),
        'profile'=>mysqli_real_escape_string($conn, $_POST['profile'])
    );
    $sql = "UPDATE author
            SET
            name = '{$filtered['name']}',
            profile = '{$filtered['profile']}'
            WHERE id = {$filtered['id']};
    ";
    $result = mysqli_query($conn, $sql);
    if($result == false){
        echo "저장하는 과정에서 문제가 생겼읍니다.";
        error_log(mysqli_error($conn));  //에러값은 아파치 에러로그에 저장되게 하는 코드
    } else {
        header('Location: author.php?id='.$filtered['id']); //주소에 id값을 추가하여 리다이렉션
    }
    ?>

     

    -author.php(20강-delete) 코드리뷰

                        <td>
                            <form action="process_delete_author.php" method="POST" onsubmit="if(!confirm('sure?')) {return false;}"> //onsubmit속성은 js문법을 담는데, 제출시의 명령을 수행함.
    //confirm()함수는 브라우저에서 확인,취소를 선택하는 창을 띄우며 취소시에 false를 반환함.
    //if문이 실행되면 return false를 통해 form action이 취소됨
                                <input type="hidden" name="id" value="<?=$filtered['id']?>">
                                <input type="submit" value="delete">
                            </form>   //delete를 post방식으로 하기 위해 a태그가 아닌 form태그 형성.
                        </td>

    -process_delete_author.php 코드리뷰

    <?php
    $conn = mysqli_connect("localhost:81", "root", "password", "opentutorials2");
    settype($_POST['id'], "integer");
    $filtered = array(
        'id'=>mysqli_real_escape_string($conn, $_POST['id'])
    );

    $sql = "DELETE FROM topic
            WHERE author_id = {$filtered['id']} //author가 삭제됬을때 author의 이름으로 적은 글들도 삭제하는 sql문
    ";
    $result = mysqli_query($conn, $sql);  

    $sql = "DELETE FROM author
            WHERE id = {$filtered['id']} //author테이블에서 지정된 author가 포함된 행을 삭제하는 sql문
    ";
    $result = mysqli_query($conn, $sql);
    if($result == false){
        echo "삭제하는 과정에서 문제가 생겼읍니다.";
        error_log(mysqli_error($conn));  //에러값은 아파치 에러로그에 저장되게 하는 코드
    } else {
        header('Location: author.php');
    }
    ?>

    '개발공부 > MySQL' 카테고리의 다른 글

    2023_09_02 MySQL&PHP 공부정리  (0) 2023.09.03
    2023_09_01 MySQL&PHP 공부정리  (0) 2023.09.02
    2023_08_31 MySQL&PHP 공부정리  (0) 2023.08.31
    2023_08_31 MySQL 공부정리  (0) 2023.08.31
    2023_08_30 MySQL 공부정리  (0) 2023.08.30
Designed by Tistory.