22. 보안

https://www.opentutorials.org/course/1688/9471



1) 보안 1

최고의 보안 담당자는 우리 시스템에 침입한 크래커


최고의 보안전문가만이 시스템을 지킬 수 있을까?

- 보안의 중요성과 보안에 대한 좋은 습관을 가질 필요가 있다.

- 좋은 습관을 가지고 몇 가지 지침들만 잘 따라주면 수많은 외부적 공격으로부터 시스템을 보호하는 효과를 가질 수 있다.



2) 보안 2 (escaping)

자바스크립트는 중요한 정보들을 탈취해서 몰래 자신들의 서버에 전송하는 능력을 가지고 있다.


사용자가 잘못된 사이트에 입력하는 정보를 알아내서 사용자의 내밀한 정보를 캐내는 나쁜 짓을 할 수 있다.

→ 피싱


문제해결 방법

- 사용자가 등록한 정보 안에는 스크립트 코드를 입력할 수 없음

- 입력한 정보가 HTML로 표현되게 하는 기법 사용


         

- 사용자가 스크립트 코드를 입력하면 그대로 실행되는 문제 발생


HTML Entity : https://dev.w3.org/html5/html-author/charref


htmlspecialchars()

- 자동변환 내장함수

- HTML의 코드로 인식될 수 있는 문자열의 일부내용을 HTML Entity로 변환하여 출력

- 보안을 높이는데 사용되는 중요한 API

- 사용자가 입력한 스크립트 코드를 무력화시키고, 화면에 출력할 수 있음


php/5.php

1
2
3
4
5
6
7
8
9
10
11
<html>
  <head>
    <meta charset = "utf-8">
    <title></title>
  </head>
  <body>
    <?php
       echo htmlspecialchars('<script>alert(1);</script>');
    ?>
  </body>
</html>
cs


- javascript를 실행하지 않는다.


사용자가 입력한 정보는 모두 공격의 대상이 될 수 있으므로 htmlspecialchars()로 감싸줘야 한다.

index.php

    


- 원하지 않는 태그들까지 HTML Entity로 변환되는 문제 발생

ex) <H2>, <ul>, <li>, <a> 등

- strip_tags() API로 해결


strip_tags()

http://php.net/manual/kr/function.strip-tags.php

- 주어진 str에서 모든 HTML과 PHP 태그를 제거한 문자열을 반환

- 선택적인 두번째 인수로 제거하지 않을 태그를 지정할 수 있음


index.php (escaping 기법 추가)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <link rel="stylesheet" type="text/css" href="/style.css">
  </head>
  <body id="target">
    <header>
      <img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩">
      <h1><a href="/index.php">JavaScript</a></h1>
    </header>
    <nav>
      <ol>
      <?php
        while($row=mysqli_fetch_assoc($result)) {
          echo '<li><a href="/index.php?id='.$row['id'].'">'.htmlspecialchars($row['title']).'</a></li>'."\n";
        }
      ?>
      </ol>  
    </nav>
    <div id="control">
      <input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
      <input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
      <a href="write.php">쓰기</a
    </div>
    <article>
      <?php
        if(empty($_GET['id']) === false) {
          $sql='SELECT topic.id, title, name, description FROM topic LEFT JOIN user ON topic.author = user.id WHERE topic.id='.$_GET['id'];
          $result = mysqli_query($conn,$sql);
          $row = mysqli_fetch_assoc($result);
          echo '<h2>'.htmlspecialchars($row['title']).'</h2>';
          echo'<p>'.htmlspecialchars($row['name']).'</p>';
          echo strip_tags($row['description'], '<a><h1><h2><h3><h4><h5><ul><ol><li>');
        }
      ?>
    </article>
  </body>
</html>
cs




3) 보안 3 

SQL Injection

- '1=1' 이라는 조건은 무조건 참



- ' or 1=1 로 인해 무조건 참이 되면서 로그인 성공


mysqli_real_escape_string()

- SQL문 안에서 특수한 기호가 있는 정보가 포함되어 있다면, 그 앞에 escape(역슬래시)를 붙여줌

- MySQL 서버는 역슬래스가 붙어있는 기호를 SQL문의 특수한 키워드로 생각하지 않고 문자로 처리


/phpjs/14.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $name = mysqli_real_escape_string($conn$_GET['name']);
  $password = mysqli_real_escape_string($conn$_GET['password']);
  $sql = "SELECT * FROM user WHERE name='".$name."' AND password='".$password."'";
  echo $sql;
  $result = mysqli_query($conn$sql);
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
  </head>
  <body>
    <?php
      if($result->num_rows == "0"){
        echo "뉘신지?";
      } else {
        echo "안녕하세요. 주인님";
      }
    ?>
  </body>
</html>
cs





※ process.php 개선

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
  $conn = mysqli_connect("localhost""root"111111);
  mysqli_select_db($conn"opentutorials");
 
  $title = mysqli_real_escape_string($conn$_POST['title']);
  $author = mysqli_real_escape_string($conn$_POST['author']);
  $description = mysqli_real_escape_string($conn$_POST['description']);
 
  $sql = "SELECT * FROM user WHERE name='".$author."'";
  $result  = mysqli_query($conn$sql);
  if($result->num_rows == 0){
    $sql = "INSERT INTO user (name, password) VALUES('".$author."', '111111')";
    mysqli_query($conn$sql);
    $user_id = mysqli_insert_id($conn);
  } else {
    $row = mysqli_fetch_assoc($result);
    $user_id = $row['id'];
  }
  $sql = "INSERT INTO topic (title,description,author,created) VALUES('".$title."', '".$description."', '".$user_id."', now())";
  $result = mysqli_query($conn$sql);
  header('Location: http://localhost/index.php');
?>
cs




20. 관계형 데이터베이스 이론

https://www.opentutorials.org/course/1688/9427



데이터베이스 ⊃ 관계형 데이터베이스(MySQL, MS-SQL, Oracle), 객체형 데이터베이스, 계층형 데이터베이스, NoSQL


관계형 데이터베이스(Relational Database)

- JOIN과 같은 것을 통해서, 두 개의 테이블이 서로 긴밀하게 관계를 맺고 있음

ex) SELECT title, name FROM topic LEFT JOIN user ON topic.author = user.id

- FROM topic : topic 정보를 조회하겠다.

- JOIN user : topic 테이블과 user 테이블을 결합해라.

- LEFT JOIN : 왼쪽 정보를 기준으로 테이블을 결합하라.

- topic.author=user.id : topic의 author와 user의 id 값을 같게 해라.

- SELECT title, name : title과 name 컬럼만 가져와라.


→ topic과 name 테이블은 물리적으로 존재하는 테이블

   위 SQL문의 결과로 나오는 테이블은 SQL이 시키는대로 조합해서 만든 가상의 테이블(논리적인 테이블)



21. 관계형 데이터베이스 실습

https://www.opentutorials.org/course/1688/9428



1) 관계형 데이터베이스 실습 1

opentutorials.sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
SET FOREIGN_KEY_CHECKS=0;
 
-- ----------------------------
-- Table structure for `topic`
-- ----------------------------
DROP TABLE IF EXISTS `topic`;
CREATE TABLE `topic` (
  `id` int(11NOT NULL AUTO_INCREMENT,
  `title` varchar(100NOT NULL,
  `description` text NOT NULL,
  `author` int(11NOT NULL,
  `created` datetime NOT NULL,
  PRIMARY KEY (`id`)
ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of topic
-- ----------------------------
INSERT INTO `topic` VALUES ('1''About JavaScript''<h3>Desctiption</h3>\r\n<p>JavaScript  is a dynamic computer programming language. It is most commonly used as part of web browsers, whose implementations allow client-side scripts to interact with the user, control the browser, communicate asynchronously, and alter the document content that is displayed.</p>\r\n<p>\r\nDespite some naming, syntactic, and standard library similarities, JavaScript and Java are otherwise unrelated and have very different semantics. The syntax of JavaScript is actually derived from C, while the semantics and design are influenced by the Self and Scheme programming languages.\r\n</p>\r\n<h3>See Also</h3>\r\n<ul>\r\n  <li><a href=\"http://en.wikipedia.org/wiki/Dynamic_HTML\">Dynamic HTML and Ajax (programming)</a></li>\r\n  <li><a href=\"http://en.wikipedia.org/wiki/Web_interoperability\">Web interoperability</a></li>\r\n  <li><a href=\"http://en.wikipedia.org/wiki/Web_accessibility\">Web accessibility</a></li>\r\n</ul>\r\n''1''2015-03-31 12:14:00');
INSERT INTO `topic` VALUES ('2''Variable and Constant''<h3>Desciption</h3>\r\n\r\nIn computer programming, a variable or scalar is a storage location paired with an associated symbolic name (an identifier), which contains some known or unknown quantity or information referred to as a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution.\r\n\r\n<h3>See Also</h3>\r\n<ul>\r\n<li>Non-local variable</li>\r\n<li>Variable interpolation</li>\r\n</ul>\r\n''3''2015-05-14 10:04:00');
INSERT INTO `topic` VALUES ('3''Opeartor''<h2>Operator</h2>\r\n<h3>Description</h3>\r\n<p>Programming languages typically support a set of operators: constructs which behave generally like functions, but which differ syntactically or semantically from usual functions</p>\r\n<p>Common simple examples include arithmetic (addition with +, comparison with >) and logical operations (such as AND or &&). </p>\r\n''1''2015-06-18 05:00:00');
INSERT INTO `topic` VALUES ('4''Conditional''<h3>Description</h3>\r\n<p>In computer science, conditional statements, conditional expressions and conditional constructs are features of a programming language which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false. Apart from the case of branch predication, this is always achieved by selectively altering the control flow based on some condition.</p>\r\n<p>In imperative programming languages, the term \"conditional statement\" is usually used, whereas in functional programming, the terms \"conditional expression\" or \"conditional construct\" are preferred, because these terms all have distinct meanings.</p>\r\n<h3>See Also</h3>\r\n<ul>\r\n<li><a href=\"http://en.wikipedia.org/wiki/Branch_(computer_science)\" title=\"Branch (computer science)\">Branch (computer science)</a></li>\r\n<li><a href=\"http://en.wikipedia.org/wiki/Conditional_compilation\" title=\"Conditional compilation\">Conditional compilation</a></li>\r\n<li><a href=\"http://en.wikipedia.org/wiki/Dynamic_dispatch\" title=\"Dynamic dispatch\">Dynamic dispatch</a> for another way to make execution choices</li>\r\n<li><a href=\"http://en.wikipedia.org/wiki/McCarthy_Formalism\" title=\"McCarthy Formalism\">McCarthy Formalism</a> for history and historical references</li>\r\n<li><a href=\"http://en.wikipedia.org/wiki/Named_condition\" title=\"Named condition\" class=\"mw-redirect\">Named condition</a></li>\r\n<li><a href=\"http://en.wikipedia.org/wiki/Test_(Unix)\" title=\"Test (Unix)\">Test (Unix)</a></li>\r\n<li><a href=\"http://en.wikipedia.org/wiki/Yoda_conditions\" title=\"Yoda conditions\">Yoda conditions</a></li>\r\n</ul>''2''2015-07-25 00:00:00');
INSERT INTO `topic` VALUES ('5''Function''A function model or functional model in systems engineering and software engineering is a structured representation of the functions (activities, actions, processes, operations) within the modeled system or subject area.''2''0000-00-00 00:00:00');
INSERT INTO `topic` VALUES ('6''Object''In computer science, an object is a location in memory having a value and possibly referenced by an identifier. An object can be a variable, a data structure, or a function. In the class-based object-oriented programming paradigm, \"object\" refers to a particular instance of a class where the object can be a combination of variables, functions, and data structures. In relational database management, an object can be a table or column, or an association between data and a database entity (such as relating a person\'s age to a specific person)''3''0000-00-00 00:00:00');
 
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11NOT NULL AUTO_INCREMENT,
  `name` varchar(20NOT NULL,
  `password` varchar(30NOT NULL,
  PRIMARY KEY (`id`)
ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1''egoing''111111');
INSERT INTO `user` VALUES ('2''jin''222222');
INSERT INTO `user` VALUES ('3''k8805''333333');
INSERT INTO `user` VALUES ('4''sorialgi''444444');
INSERT INTO `user` VALUES ('5''lily''555555');
INSERT INTO `user` VALUES ('6''happydeveloper''666666');
cs


        

                            

※ index.php에서 부족한 부분 채우기

index.php (line 8 추가)

1
2
3
4
5
6
7
8
9
10
11
12
<article>
    <?php
        if(empty($_GET['id']) === false) {
        $sql='SELECT * FROM topic WHERE id='.$_GET['id'];
        $result = mysqli_query($conn,$sql);
        $row = mysqli_fetch_assoc($result);
        echo '<h2>'.$row['title'].'</h2>';
        echo'<p>'.$row['author'].'</p>';
        echo $row['description'];
        }
    ?>
</article>
cs



 2) 관계형 데이터베이스 실습 2

index.php (<article> 수정)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <link rel="stylesheet" type="text/css" href="/style.css">
  </head>
  <body id="target">
    <header>
      <img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩">
      <h1><a href="/index.php">JavaScript</a></h1>
    </header>
    <nav>
      <ol>
      <?php
        while($row=mysqli_fetch_assoc($result)) {
          echo '<li><a href="/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";
        }
      ?>
      </ol>  
    </nav>
    <div id="control">
      <input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
      <input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
      <a href="write.php">쓰기</a
    </div>
    <article>
      <?php
        if(empty($_GET['id']) === false) {
          $sql='SELECT topic.id, title, name, description FROM topic LEFT JOIN user ON topic.author = user.id WHERE topic.id='.$_GET['id'];
          $result = mysqli_query($conn,$sql);
          $row = mysqli_fetch_assoc($result);
          echo '<h2>'.$row['title'].'</h2>';
          echo'<p>'.$row['name'].'</p>';
          echo $row['description'];
        }
      ?>
    </article>
  </body>
</html>
cs



3) 관계형 데이터베이스 실습 3

topic 테이블에 데이터를 추가해보자


process.php (author에 따른 id 값 가져오는 부분 추가)

1
2
3
4
5
6
7
8
9
10
11
<?php
  $conn = mysqli_connect("localhost""root","");
  mysqli_select_db($conn"opentutorials");
  $sql="SELECT * FROM user WHERE name='".$_POST['author']."'";
  $result = mysqli_query($conn$sql);
  $row = mysqli_fetch_assoc($result);
  $user_id=$row['id'];
  $sql = "INSERT INTO topic (title,description,author,created) VALUES('".$_POST['title']."', '".$_POST['description']."', '".$user_id."', now())";
  $result = mysqli_query($conn$sql);
  header('Location: /index.php'); // redirection
?>
cs



            


위의 코드에서 user 테이블에 등록되어 있지 않은 사용자는 id 값을 가져올 수 없다.

process.php (조건문 추가)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
  $conn = mysqli_connect("localhost""root","");
  mysqli_select_db($conn"opentutorials");
  $sql="SELECT * FROM user WHERE name='".$_POST['author']."'";
  $result = mysqli_query($conn$sql);
 
  if($result->num_rows == 0){
    $sql = "INSERT INTO user (name, password) VALUES('".$_POST['author']."', '111111')";
    mysqli_query($conn$sql);
    $user_id = mysqli_insert_id($conn);
  } else {
    $row = mysqli_fetch_assoc($result);
    $user_id=$row['id'];
  }
 
  $sql = "INSERT INTO topic (title,description,author,created) VALUES('".$_POST['title']."', '".$_POST['description']."', '".$user_id."', now())";
  $result = mysqli_query($conn$sql);
  header('Location: /index.php'); // redirection
?>
cs

- num_rows : 데이터베이스에서 쿼리의 결과로 나온 레코드들의 개수 카운트



             



19. 데이터베이스(MySQL) 실습

https://www.opentutorials.org/course/1688/9398



1) MySQL 실습 1


PHP의 역할

- 데이터베이스 시스템과 웹서버 사이에서 중계자와 같은 역할

→ 처리하려는 .php 파일에 데이터베이스에 있는 정보를 가져와서 웹페이지로 만들라는 코드가 들어가 있다면, PHP가 중간에서 데이터베이스에 있는 정보를 가져와서 웹페이지를 만듬

→ 이런 맥락에서 PHP 애플리케이션을 미들웨어라고도 부름


mysqli

PHP에 내장되어 있는 API

PHP가 위와 같은 역할을 수행하기 위해 사용


실습환경 구축

 

 MySQL monitor

 mysqli

 서버 접속

 mysql -hlocalhost -uroot -p111111;

 $conn = mysqli_connect('localhost', 'root', '111111');

 DB 선택

 mysql> use opentutorials

 mysqli_select_db($conn, 'opentutorials'); 

 조회

 mysql> SELECT * FROM topic;

 $result = mysqli_query($conn, 'SELECT * FROM topic');

 출력

 $row = mysqli_fetch_assoc($result);

 $row['title'];

 $row['description'];


※ 연관 배열

ex.php

1
2
3
4
5
6
7
8
9
10
11
<?php
    // 일반 배열
    $a = array("About JavaScript""JavaScript is...");
    echo $a[0];
 
    echo "<br />";
    
    // 연관 배열
    $b = array("title" => "About JavaScript""description" => "JavaScript is...");
    echo $b["title"];
?>
cs



2) MySQL 실습 2

ex.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
  $row=mysqli_fetch_assoc($result); // 조회한 내용 중 첫번째 행의 데이터
  echo $row['id'];
  echo $row['title'];
  echo "<br />";
 
  $row=mysqli_fetch_assoc($result); // 조회한 내용 중 두번째 행의 데이터
  echo $row['id'];
  echo $row['title'];
  echo "<br />";
 
  $row=mysqli_fetch_assoc($result); // 조회한 내용 중 세번째 행의 데이터
  echo $row['id'];
  echo $row['title'];
  echo "<br />";
 
  $row=mysqli_fetch_assoc($result); // 조회한 내용 중 네번째 행의 데이터 -> 데이터 X
  var_dump($row);
?>
cs


- php에서 NULL == False


index.php (database 부분 추가, <nav> 수정)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <link rel="stylesheet" type="text/css" href="/style.css">
  </head>
  <body id="target">
    <header>
      <img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩">
      <h1><a href="/index.php">JavaScript</a></h1>
    </header>
    <nav>
      <ol>
      <?php
        while($row=mysqli_fetch_assoc($result)) {
          echo '<li><a href="/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";
        }
      ?>
      </ol>  
    </nav>
    <div id="control">
      <input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
      <input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
    </div>
    <article>
      <?php
      if(empty($_GET['id']) == false) {
        echo file_get_contents($_GET['id'].".txt");
      }
      ?>
    </article>
  </body>
</html>
cs




3) MySQL 실습 3

style.css (추가부분)

1
2
3
4
5
6
7
8
9
nav ol{
  list-style:none;
  padding:0;
}
article{
  float:left;
  padding:20px;
  width:500px;
}
cs


index.php (<article> 수정)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <link rel="stylesheet" type="text/css" href="/style.css">
  </head>
  <body id="target">
    <header>
      <img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩">
      <h1><a href="/index.php">JavaScript</a></h1>
    </header>
    <nav>
      <ol>
      <?php
        while($row=mysqli_fetch_assoc($result)) {
          echo '<li><a href="/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";
        }
      ?>
      </ol>  
    </nav>
    <div id="control">
      <input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
      <input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
    </div>
    <article>
      <?php
        if(empty($_GET['id']) === false) {
          $sql='SELECT * FROM topic WHERE id='.$_GET['id'];
          $result = mysqli_query($conn,$sql);
          $row = mysqli_fetch_assoc($result);
          echo '<h2>'.$row['title'].'</h2>';
          echo $row['description'];
        }
      ?>
    </article>
  </body>
</html>
cs



4) MySQL 실습 4

<p> 태그

- paragraph : 단락


<input type="text">

- 한 줄의 텍스트 입력창


<textarea> 태그

- 여러줄의 텍스트 입력


<input type="submit">

- submit : 제출하다

- 사용자가 입력한 정보들을 서버로 전송


<form> 태그

- 입력 양식을 만들 때 사용

- 사용자가 입력한 정보를 서버로 전송할 때 사용하는 것 

- 속성

* action : control들의 입력된 정보를 action 속성에 지정된 애플리케이션에게 전송

* method : 폼을 서버에 전송할 HTTP 메소드(GET 또는 POST)


※ GET 방식을 이용했을 때, 정보의 길이가 길면 오류 발생 

→ 긴 정보는 URL에 입력값을 통해서는 전송할 수 없음

→ POST 방식 사용


3.html

1
2
3
4
5
6
7
8
9
10
11
12
13
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
  </head>
  <body>
    <form action="/php/3.php" method="POST">
      <p>제목 : <input type="text" name="title"></p>
      <p>본문 : <textarea name="description"></textarea></p>
      <input type="submit">
    </form>
  </body>
</html>
cs


3.php

1
2
3
4
5
<?php
  echo $_POST['title'];
  echo "<br>";
  echo $_POST['description'];
?>
cs



5) MySQL 실습 5

DESC [table 명];

- 해당 테이블의 구조를 기술해줌


now()

- MySQL의 함수

- MySQL이라는 데이터베이스가 제공하는 API

- 현재 날짜 및 시간 반환


index.php (control에 <a> 태그 추가)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <link rel="stylesheet" type="text/css" href="/style.css">
  </head>
  <body id="target">
    <header>
      <img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩">
      <h1><a href="/index.php">JavaScript</a></h1>
    </header>
    <nav>
      <ol>
      <?php
        while($row=mysqli_fetch_assoc($result)) {
          echo '<li><a href="/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";
        }
      ?>
      </ol>  
    </nav>
    <div id="control">
      <input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
      <input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
      <a href="write.php">쓰기</a
    </div>
    <article>
      <?php
        if(empty($_GET['id']) === false) {
          $sql='SELECT * FROM topic WHERE id='.$_GET['id'];
          $result = mysqli_query($conn,$sql);
          $row = mysqli_fetch_assoc($result);
          echo '<h2>'.$row['title'].'</h2>';
          echo $row['description'];
        }
      ?>
    </article>
  </body>
</html>
cs


write.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<?php
  $conn = mysqli_connect('localhost''root''');
  mysqli_select_db($conn'opentutorials');
  $result = mysqli_query($conn'SELECT * FROM topic');
?>
 
<!DOCTYPE html>
<html>
  <head>
    <meta charset = "utf-8">
    <link rel="stylesheet" type="text/css" href="/style.css">
  </head>
  <body id="target">
    <header>
      <img src="https://s3.ap-northeast-2.amazonaws.com/opentutorials-user-file/course/94.png" alt="생활코딩">
      <h1><a href="/index.php">JavaScript</a></h1>
    </header>
    <nav>
      <ol>
      <?php
        while($row=mysqli_fetch_assoc($result)) {
          echo '<li><a href="/index.php?id='.$row['id'].'">'.$row['title'].'</a></li>'."\n";
        }
      ?>
      </ol>  
    </nav>
    <div id="control">
      <input type="button" value="white" onclick="document.getElementById('target').className='white'"/>
      <input type="button" value="black" onclick="document.getElementById('target').className='black'"/>
      <a href="write.php">쓰기</a
    </div>
    <article>
      <form action="/process.php" method="post">
        <p>제목 : <input typt="text" name="title"></p>
        <p>작성자 : <input typt="text" name="author"></p>
        <p>본문 : <textarea name="description"></textarea>
        <input type="submit" name="name">
      </form>
    </article>
  </body>
</html>
cs


process.php

1
2
3
4
5
6
7
<?php
  $conn = mysqli_connect("localhost""root","");
  mysqli_select_db($conn"opentutorials");
  $sql = "INSERT INTO topic (title,description,author,created) VALUES('".$_POST['title']."', '".$_POST['description']."', '".$_POST['author']."', now())";
  $result = mysqli_query($conn$sql);
  header('Location: /index.php'); // redirection
?>
cs


LAN의 정의 및 특징


1. 근거리 통신망(LAN)의 정의와 특징

근거리 통신망(LAN : Local Area Network)

- 여러 대의 컴퓨터와 주변장치 등이 통신 네트워크를 구성하여 통신하는 망

- 학교, 건물, 사무실, 대학 등과 같이 비교적 가까운 거리에 한정되어 있는 망


근거리 통신망의 특징

- 네트워크 내의 다양한 자원을 서로 공유하고 필요한 정보를 서로 교환할 수 있는 사설 네트워크

* 단일 기관의 소유

* 네트워크 구성의 최소의 단위

* 다양한 통신장치와의 연결성

* 네트워크 확장 및 재배치 용이

* 다양한 데이터 처리(데이터, 음성, 영상 등)

* 네트워크 내의 어떤 기기간에도 전송이 가능

* MAN, WAN의 구성요소

* 데이터 전송에 대한 높은 신뢰성


근거리 통신망의 도입효과

- 분산처리의 실현

* 현재의 집중 처리 방식에서 업무별 분산 처리 가능

* 고가의 대형 시스템을 중저가의 중소형 시스템으로 대체 이용 가능

- 통합된 네트워크 관리

- 고속의 데이터 전송

- 자원 공유

* 주변장치, 소프트웨어, 자료의 공유 가능

- 효과적인 시스템 이용

* 파일 전송에 의한 데이터 교환 가능

- 통신기기간 통신

* 통신기기를 연결하여 데이터의 전송 및 파일 서버의 프로그램, 프린터 주변기기 공유


2. 근거리 통신망(LAN)의 등장배경

1970년대 초

- 미국의 제록스(Xerox)사의 PARC에서 LAN에 대한 학문적 연구로부터 시작


1976년

- 미국의 제록스(Xerox)에서 발표한 이더넷(Ethernet) 이후 급속한 발전을 가져옴

- 전송속도 : 3Mbps


1979년

- 미국의 제록스(Xerox)에서 전송속도 10Mbps를 발표함으로써 표준화가 활성화함


1980년

- 9월에 이더넷(Ethernet) 표준규격 버전 1.0이 발표됨으로써 본격적인 발전 시작


3. 근거리 통신망(LAN)의 발전과정

1950년대 ~ 1960년대 전반

- Batch처리 방식(전형적인 Local Batch)

: 기간이나 양을 정해서 데이터를 수집한 후 일괄적으로 처리하는 방식

ex) OMR 카드


1960년대

- 컴퓨터 처리 속도의 비약적인 발전

- 멀티 프로그램이 가능한 운영체제 등장

- 컴퓨터와 터미널 간의 온라인이용

- 컴퓨터 이용의 공간적 제약을 벗어남


1970년대

- 컴퓨터 이용에 대한 수요가 더욱 다양화되고 증진됨

- 다양한 기술과 저렴한 가격의 미니 컴퓨터가 장착

- 대용량 디스크와 주변장치들의 공유 필요

- 데이터의 중복, 제한된 연산능력, 한정된 컴퓨터 자원 등의 문제점을 보완하기 위해 컴퓨터간의 통신 필요성 증대로 통신장비 및 통신 S/W 개발

- 고도의 조직적인 네트워크 필요성 등장(원거리 통신망(WAN)의 출현배경)

- 분산처리 체계의 확립


1980년대

- 개인용 컴퓨터 대량 보금(비전문가의 컴퓨터 이용시대)

- 사무실, 공장, 실험실 등에서 다양한 정보 처리 수요 폭발

- 모든 부서에서 컴퓨터 설치, 설치된 컴퓨터 및 주변기기와 타사무자동화 기기들간의 통신 처리 필요성

- 기기들간에 신속하고 용이하며 신뢰성 있는 정보를 교환할 수 있는 체계의 필요성 증대

→ LAN이 등장하게 되는 배경 형성


1990년대 ~ 현재

- 인터넷의 대중적 보급


4. 근거리 통신망(LAN)의 구성요소

근거리 통신망 구성요소

- 여러개의 근거리 통신망을 상호 접속하여 하나의 통신망으로 형성하기 위해서 사용되는 장비는 전송매체, 네트워크 인터페이스 카드, 리피터, 허브, 브리지, 라우터, 게이트웨이 등이 있음

- LAN과 WAN을 서로 연결하기 위해서는 LAN의 구성요소들 중 리피터, 브리지, 라우터, 게이트웨이를 사용하여 서로 다른 LAN들을 연결

→ 이러한 장비들을 인터네트워킹 장비라 부름


전송 매체

- 트위스트 페어 케이블(Twisted Pair Cable)

- 동축 케이블(Coaxial Cable)

- 광섬유 케이블(Optical Fiber Cable)


근거리 통신망 구성요소

- NIC(Network Interface Card)

: 일명 LAN Card라고 불림

: 컴퓨터를 전송매체에 연결해주는 장치

: 디지털 정보를 전기신호로 변환, 충돌을 회피하여 신호를 케이블로 전송

: 데이터 전송은 패킷(Packet) 단위로 전송

: 전송매체의 종류, 접속형태(Topology), 액세스 방식에 영향을 끼침

: Ring, Bus 접속형태 등을 복합적 연결 가능

- 리피터(Repeater)

: 증폭기 역할

: 거리가 증가할수록 감쇄되는 신호를 재생시키는 장치

- 허브(Hub)

: 네트워크 케이블 집중장치

: 중앙의 제어장치를 중심으로 Point-to-Point 연결을 위한 장치


* 종류

□ 더미 허브(Dummy Hub) : 단순한 연결 기능

□ 인텔리전트 허브(Intelligent Hub) : 네트워크 관리 기능이 추가

- 브리지(Bridge)

: LAN과 LAN을 연결하여 신호를 교환하여 주는 역할

: OSI 7 Layer 2계층인 Data-Link Layer를 사용

: 분리된 장소에 설치된 두 개 이상의 LAN을 연결하여 하나의 LAN처럼 보이게 함

- 라우터(Router)

: 다른 망을 연결하기 위해 반드시 필요

: 데이터를 발신지로부터 여러 링크를 통하여 목적지까지 전달하는 책임을 가지는 OSI 7 Layer 3계층인 Network Layer 기능을 수행

: 원거리의 연결(LAN/MAN/WAN) 가능

: 라우팅 테이블(Routing Table)을 만들어서 데이터 운반

- 게이트웨이(Gateway)

: 다른 종류의 통신망 사이에 메시지를 전달할 수 있도록 해주는 장치

: 다른 종류의 서로 다른 네트워크의 특성을 상호 변환시켜 호환성 있는 정보를 전송할 수 있게 해주는 장치


5. 근거리 통신망(LAN)의 전송방식

베이스 밴드(Base Band)

- 컴퓨터나 통신장치의 디지털 출력신호를 변조하지 않고 전송로를 이용하여 그대로 전송하는 방식


- 디지털 신호를 사용하여 변조하지 않음

- 송수신 장치가 간단하고, 소요비용 저렴

- 한번에 하나의 신호만 전송 가능

- 1Km ~ 2Km 정도로 거리가 제한되어 있고, 그 이상 거리는 리피터(Repeter)를 사용

- 전송매체는 트위스트 페어 케이블, 동축 케이블을 많이 사용

- 주로 BUS 전송형태의 통신망이 많이 쓰임


브로드 밴드(Broad Band)

- 디지털 데이터를 모뎀을 이용하여 아날로그 데이터로 변조하여 전송하는 방식


- 아날로그 신호를 전송하며, 주파수 분할 다중화(FDM) 방식을 사용

- 동시에 여러 정보 전송 가능(다기능 네트워크)

- 정보의 흐름이 한 방향으로만 이루어짐

- 케이블 설계가 복잡하여 설치 비용이 높고, 유지보수가 상대적으로 어려움

- CATV에 사용 가능하고 대역폭이 넓음

- 주로 토큰 버스와 트리 접속형태의 통신망이 많이 쓰임


베이스 밴드 방식과 브로드 밴드 방식의 비교



IEEE의 LAN 표준안


1. LAN의 표준화

LAN의 표준화

- IEEE(Institute of Electrical and Electronics Engineers) 표준화 프로젝트(1985년 설립)

- 프로젝트 802와 OSI 모델과의 관계 : 데이터 링크계층(Data-link Layer)을 논리링크제어(LLC)와 매체접근제어(MAC)으로 두 서브계층으로 나눔

* 매체접근제어(MAC : Medium Access Control)은 전송매체의 종류에 따라 데이터 전송이 가능하도록 프레임의 전송을 담당

* 논리링크제어(LLC : Logic Link Control)은 데이터 링크 설정, 관리, 해제 등의 기능을 수행

- LAN에서는 물리계층(Physical Layer)과 데이터 링크계층(Data-link Layer)만 규정


프로젝트 802.

- 두 서브계층 논리링크제어(LLC)와 매체접근제어(MAC)로 나뉨

- 인터네트워킹 관련 부분을 포함하고 있는데 프로토콜이 서로 다른 통신망들 사이의 호환성을 보장하고 데이터를 교환하는 것을 허용

- 프로젝트 802의 강점은 모듈성

- LAN 관리에 필수적인 기능들을 나누어서 일반화가 가능한 부분을 표준안으로 만들 수 있음

- 각 네트워크에 특정한 부분을 별도로 분리시킬 수 있음


2. 논리링크제어(LLC)

논리링크제어(LLC : Logic Link Control)

- 상위계층과 인터페이스 기능을 수행함과 동시에 링크 제어기능인 오류제어 및 흐름제어를 함

- 논리적 링크 제어의 데이터 단위는 프로토콜 데이터 유닛(PDU)


프로토콜 데이터 유닛(PDU : Protocol Data Unit)

- HDLC와 유사한 4개의 필드로 구성


프로토콜 데이터 유닛의 형식


논리링크제어의 3가지 서비스

- 비확인 비연결형 서비스

: 논리적 연결 설정 하지 않고 흐름제어나 오류제어를 수행하지 않음

: 신뢰성 있는 높은 데이터 전달이 보장되지 않음

: 논리적 링크 제어의 상위 계층에서 오류제어 및 흐름제어 기능이 제공되는 경우 사용

: 물리적인 전송매체의 신뢰성이 우수하므로 대부분의 LAN에서 채택하여 사용

- 연결형 서비스

: HDLC에서 제공하는 서비스와 유사

: 데이터 전송 전에 논리적인 연결 설정

: 흐름제어와 오류제어 기능 수행

: 신뢰성 있는 데이터 전달 가능

- 확인 비연결형 서비스

: 논리적인 연결을 설정하지 않음

: 수신측으로부터 확인 응답을 통하여 전송 실행

: 신뢰성 있는 데이터 전달 가능



LAN의 기술


1. CSMA/CD

CSMA/CD(Carrier Sense Multiple Access with Collision Detection)

- IEEE 802.3 표준으로 정의된 네트워크에서 사용

- OSI 7 Layer에서 데이터 링크 계층의 매체접근제어(MAC)에서 동작

- 전송 기회를 잡기 위한 경쟁(contention) 방식


CSMA/CD의 진화된 과정


동작절차

① A에서 C로 데이터 전송

② A가 보낸 데이터가 C로 전송되기 전에 C가 데이터 전송을 시작 

③ C의 충돌을 감지하고 충돌신호를 모든 호스트들에게 전송

④ A는 충돌신호를 감지하고 전송을 중단한 후 회선이 깨끗해질 때까지 기다린 다음 데이터 전송을 다시 함

→ 만약, 연속적인 충돌이 16번 이상 생긴다면 각 장치는 데이터 전송을 포기하고 다른 명령이 오기를 기다림


CSMA/CD 장점

- 통신량이 적을 때 최적의 성능 발휘

- 한 개의 장치에 고장이 발생해도 전체 네트워크 내의 장치의 통신에 영향을 주지 않음


CSMA/CD 단점

- 통신량이 많을 때 충돌회수가 증가하면서 이용률이 떨어지고 지연시간의 예측 불가능


CSMA/CD(IEEE 802.3) MAC 프레임 구조

- 프리앰블(Preamble)

: 첫 번째 필드

: 0과 1을 반복하는 7바이트 포함

: 수신측에 프레임 도착 통지, 타이밍 및 시작 동기화

- 시작 프레임 지시기(Start Frame Delimiter)

: 프레임 시작을 알림

- 목적지 주소(Destination Address)

: 목적지의 물리 주소

- 발신지 주소(Source Address)

: 발신지의 물리 주소

- 타입(Type)

: 프레임에 저장된 데이터 유형

- 데이터(Data)

: 논리링크제어로부터 받은 데이터

: 46 ~ 1500 bytes 사이

- CRC(Cyclic Redundancy Check)

: 오류 검출


2. 토큰 패싱

토큰 패싱(Token Passing)

- 송신권을 부여하는 신호인 토큰(Token)이라는 데이터를 순환하여 순차적으로 옮겨가면서 전송하는 방식

- 토큰을 가진 통신장비만 송신 가능

- CSMA/CD와 같은 충돌은 발생하지 않음

- 네트워크의 접속형태에 따라 토큰 링 방식과 토큰 버스 방식으로 구분


토큰 패싱의 특징

- 데이터 전송에 있어서 충돌발생이 없으며, 확실한 데이터 전송이 이루어짐

- 주기적으로 데이터 전송이 이루어지므로 데이터 전송속도 제어 가능

- 전송량이 많은 네트워크에서 더욱 효율적


토큰 패싱의 단점

- 통신장비 수가 많아서 토큰의 순회시간이 길어지게 되면 네트워크의 속도 저하

- 토큰이 유실되었을 때 무한히 기다려야 함


토큰 버스(Token Bus)

- IEEE 802.4 표준으로 정의된 네트워크에서 사용

- 충돌에 따른 지연시간 떄문에 사용

- 물리적으로는 버스형, 논리적으로 토큰을 이용한 링형(Ring using token)이 있음

- 중요도가 다른 장치들 간에 일정한 시간 내에 정보 교환이 가능하기 때문에 공장자동화와 프로세스 제어에 많이 사용


토큰 버스의 특징

- 토큰을 사용함으로써 충돌 가능성 제거

- 스테이션 간의 우선 순위 설정 가능

- 부하가 큰 경우 CSMA/CD보다 성능 우수


토큰 버스의 단점

- 논리적으로 링 형태로 작동하기 떄문에 복잡


 토큰 링(Token Ring)

- 1984년 IBM에 의해서 개발

- OSI 7 Layer에서 데이터 링크 계층의 매체접근제어(MAC)에서 동작

- 논리적인 링의 접속형태

- 전송속도는 4Mbps 및 16Mbps

- 전송제어기법은 토큰 패싱 기법 사용

- IEEE 802.5의 표준으로 정의된 네트워크에서 사용


토큰 링의 장점과 단점

- 장점 : 각 스테이션에 공정한 접속 기회를 제공하며 우선 순위를 두어서 통신량의 조절 가능

- 단점 : 토큰 관리 필요


토큰 링의 동작절차

① 토큰은 링형 구조에서 전송할 컴퓨터를 기다리면서 돌고 있다.

② 컴퓨터 A는 컴퓨터 D에게 전송하기 위해 토큰을 받은 후 데이터를 컴퓨터 D에게로 전송한다.

③ 데이터를 받은 컴퓨터 D는 데이터를 복사한 후, 데이터를 다시 링형 구조로 보내지게 되어 링을 따라 돈다.

④ 링을 따라 돌다가 컴퓨터 A에 도착하여 전송이 성공적으로 이루어졌음을 알린다.


※ CSMA/CD와 토큰 패싱의 비교


3. 이더넷

이더넷

- IEEE의 802.3 표준의 기초

- 근거리에 위치한 사용자 기기 및 컴퓨터 간의 데이터 전송이 가능

- 데이터 전송을 제어하는 기법은 CSMA/CD을 사용

- 데이터의 전송 능력에 따라 10Mbps와 100Mbps로 구분

- 이더넷 사양은 OSI 참조 모델의 물리적 계층과 데이터 링크 계층과 같은 기능을 수행

- 현재 가장 널리 사용되는 네트워크의 연결방법


이더넷의 종류

- 이더넷의 접속 형태 : X Base Y

* X : 전송속도를 나타냄

* Base or Broad : 베이스밴드 전송방법 혹은 브로드밴드 전송방법을 나타냄

* Y : 전송 가능한 세그먼트의 거리를 나타냄


4. 스위칭 LAN

스위칭 LAN(Swiching Local Area Network)의 도입배경

- 기존 이더넷의 문제점

: 다중매체 접속 방법

: 물리적으로는 스타형이며 논리적으로는 버스형

: 하나의 스테이션이 프레임을 보내면 나머지 모든 포트로 프레임 전송

: 두 스테이션이 동시에 프레임을 보내면 충돌 발생


스위칭 LAN

- 스위칭 LAN은 기존의 네트워크를 연결해주는 허브를 스위치로 바꾸어 두 통신 사용자에게 독립적인 통신매체의 사용을 보장하는 방법

- 허브를 스위치로 대체

- 두 통신 사용자에게 독립적인 통신매체의 사용을 보장하는 방법

- 충돌이 발생하지 않음


5. 고속 이더넷

고속 이더넷

- 이더넷 기술을 계승한 것으로 전송 매체 상의 데이터 전송 속도를 100Mbps로 고속화한 LAN

- 100Mbps로 동작

- 표준안의 총괄적인 명칭은 100BASE-T

- 100BASE-T 옵션은 모두 802.3 MAC 프로토콜과 프레임 형식을 사용

- 모든 100BASE-T 규격은 10BaseT의 성형 토폴로지와 유사

- 전송 매체의 종류에 따른 다수의 대체 방안을 정의


고속 이더넷의 종류

- 100Base-TX

: 모든 노드들이 연결된 형태

: 문제해결이 쉽고 오류에 강함

: 여분의 경로로 인해 오류의 영향을 적게 받음

- 100Base-FX

: 두 개의 광섬유 케이블 사용

: 신호방식은 NRZI

: 스테이션과 허브간의 최대 간격은 2000m

- 100Base-T4

: 기존의 전화선을 이용하여 고속 이더넷 구현

: 4쌍의 카테고리 3 UTP 케이블 사용

: 각 방향으로 동시에 3쌍이 데이터 전송에 사용(2쌍은 양방향, 1쌍은 단방향)

: 각 쌍에 33.66Mbps 씩 전송


6. 기가비트 이더넷

기가비트 이더넷

- 1995년 후반, IEEE802.3 위원회는 이더넷 구성 형태에서 초당 기가비트의 속도로 데이터를 전달하는 방법 연구

- 새로운 매체와 전송 규격이 정의되는 동안 CSMA/CD와 10Mbps의 기존 이더넷 형태를 유지

- 100BASE-T 및 10BASE-T와 호환이 가능하며 원할하게 이전 가능

- 매체 및 전송에 관한 규격은 광섬유를 사용하여 광 채널의 물리 계층의 규격을 도입하여 사용

- 고속 이더넷의 중추적인 역할로 주로 사용


+ Recent posts