본 게시글은 유튜브 생활코딩 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.

생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.

생활코딩 유튜브

 

생활코딩

일반인에게 프로그래밍을 알려주는 온라인/오프라인 활동 입니다.

www.youtube.com

생활코딩 사이트

 

생활코딩

hello world 생활코딩의 세계에 오신 것을 환영합니다. 생활코딩은 일반인들에게 프로그래밍을 알려주는 무료 온라인, 오프라인 수업입니다.  어떻게 공부할 것인가를 생각해보기 전에 왜 프로그래밍을 공부하는 이유에 대한 이유를 함께 생각해보면 좋을 것 같습니다. 아래 영상을 한번 보시죠. 온라인 강의 소개 입문자의 가장 큰 고충은 '무엇을 모르는지 모르는 상태'일 겁니다. 온라인에는 프로그래밍을 익히는 데 필요한 거의 모든 정보가 있지만, 이 지식들은

opentutorials.org

생활코딩 WEP3 PHP & MySQL을 수강하기 위한 선수과목인

WEB2 - PHPDATABASE2 - MySQL에 대한 수강 기록입니다.

수강 일정은 야학의 수강계획표에 따릅니다.


#0.

이제부터 읽기, 쓰기, 수정, 삭제 기능을 모두 갖춘 완벽한 웹앱을 만들 것입니다. 우리가 만들 웹앱이 어떤 기능을 가지게 될 것인지를 스포일러 합니다. 

 

#1.

서버로 데이터를 전송할 때 사용하는 HTML의 기능인 form을 살펴봅니다. 또, URL을 통하지 않고 은밀하게 데이터를 전송하는 방법인 POST 방식도 알아보겠습니다. 

 

사용자의 정보를 서버쪽으로 전송할 때 사용하는 기능인 form에 대해서 알아보자.

php에서 form을 다루는 방법은 이곳에 잘 설명되어 있다.

 

PHP Form Handling

PHP Form Handling The PHP superglobals $_GET and $_POST are used to collect form-data. PHP - A Simple HTML Form The example below displays a simple HTML form with two input fields and a submit button: Example

www.w3schools.com

혹시 폼에 대한 기본적인 지식이 전무하다면 이곳을 살펴보자.

 

HTML Forms

HTML Forms An HTML form is used to collect user input. The user input is most often sent to a server for processing. The Element The HTML element is used to create an HTML form for user input:

. form elements .
The element is a container for

 

www.w3schools.com

<!--form.hmtl-->
<!doctype html>
<html>
  <body>
    <form action="form.php" method="post">
      <p><input type="text" name="title" placeholder="Title"></p>
      <p><textarea name="description"></textarea></p>
      <p><input type="submit"></p>
    </form>
  </body>
</html>

코드를 천천히 살펴보면, form.php란 곳으로 post방식을 통해 데이터를 보내는 것을 확인할 수 있다.

또한 name이란 이름의 input과 description이란 이름의 textarea가 그 데이터 안에 담기게 되며,

submit을 통해 제출되는 것을 확인할 수 있다.

그렇다면 form.html에서 데이터를 받는 곳엔 form.php에 대한 코드도 확인해보겠다.

//form.php
<?php
file_put_contents('data/'.$_POST['title'], $_POST['description']);
?>

form.php에서는 file_put_contents함수를 사용하고 있다.

이 함수에 대한 설명은 이 곳을 참조하자.

 

PHP: file_put_contents - Manual

file_put_contents (PHP 5, PHP 7) file_put_contents — Write data to a file Description file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int If filename does not exist, the file is created. Otherwise, the exi

www.php.net

공식페이지를 살펴보면 file_put_contents에 대한 Description을 아래와 같이 정의하고 있다.

file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int

여기서 filename이란 데이터를 쓸 파일의 경로를 말하며,

dat란 쓸 데이터이며 문자열, 배열 혹은 스트림 리소스가 이에 해당될 수 있다.

flag의 값은 or연산자를 통해 다양하게 조합될 수 있는데,

FILE_USE_INCLUDE_PATH, FILE_APPEND, LOCK_EX 등의 flag값이 지원되나 지금은 넘어가겠다.

따라서 이에 기반해 위 form.php 코드를 해석해본다면,

'data/' 라는 디렉토리에서 사용자가 post방식으로 제출한 'title'과 'description'을 저장하는 것을 확인할 수 있다.

여기서 혹시 form방식과 get방식에 대한 차이를 잘 모른다면 이 게시글을 참조하자.

 

HTTP Methods GET vs POST

HTTP Request Methods What is HTTP? The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers. HTTP works as a request-response protocol between a client and server. Example: A client (browser) sends an HTTP req

www.w3schools.com

 

#2.

PHP를 이용해서 불특정 다수가 웹을 통해서 글을 제출하는 방법을 살펴보겠습니다. 

 

이전 시간에 배운 form을 응용해서 글생성 기능을 구현하고자 한다.

먼저 우리의 코드에서 글을 생성하는 곳으로 이동하는 링크를 추가한 이후,

링크가 클릭되면 이동되는 곳에 대한 코드는 아래와 같다.

<?php
function print_title(){
  if(isset($_GET['id'])){
    echo $_GET['id'];
  } else {
    echo "Welcome";
  }
}
function print_description(){
  if(isset($_GET['id'])){
    echo file_get_contents("data/".$_GET['id']);
  } else {
    echo "Hello, PHP";
  }
}
function print_list(){
  $list = scandir('./data');
  $i = 0;
  while($i < count($list)){
    if($list[$i] != '.') {
      if($list[$i] != '..') {
        echo "<li><a href=\"index.php?id=$list[$i]\">$list[$i]</a></li>\n";
      }
    }
    $i = $i + 1;
  }
}
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      <?php
      print_title();
      ?>
    </title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <?php
      print_list();
      ?>
    </ol>
    <a href="create.php">create</a>
    <form action="create_process.php" method="post">
      <p>
        <input type="text" name="title" placeholder="Title">
      </p>
      <p>
        <textarea name="description" placeholder="Description"></textarea>
      </p>
      <p>
        <input type="submit">
      </p>
    </form>
  </body>
</html>

기본적으로 기존의 index.php와 코드가 유사하나,

글을 클릭했을 때 제목과 설명이 출려되는 코드 이전에 form태그를 삽입하였다.

이 form에 대한 정보는 create_process.php로 전송되는 데 그 코드는 다시 아래와 같다.

<?php
file_put_contents('data/'.$_POST['title'], $_POST['description']);
header('Location: /index.php?id='.$_POST['title']);
?>

이전 폼을 배우면서 만들었던 코드와 대동소이하나, 

제출 버튼을 누른 이후 자동으로 글을 작성한 페이지로 이동하기 위해서 header를 사용하였다.

header에 대한 공식문서는 곳을 참조

 

PHP: header - Manual

After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.  Take a look at this code, which replicates the normal download of a Javascript: Now let me explain:  I start out by checking f

www.php.net

header의 매개변수 중 하나인 Location을 이용해서 url을 이동시키고 있다.

글의 생성된 코드가 추가된 index.php 코드는 아래와 같다.

<?php
function print_title(){
  if(isset($_GET['id'])){
    echo $_GET['id'];
  } else {
    echo "Welcome";
  }
}
function print_description(){
  if(isset($_GET['id'])){
    echo file_get_contents("data/".$_GET['id']);
  } else {
    echo "Hello, PHP";
  }
}
function print_list(){
  $list = scandir('./data');
  $i = 0;
  while($i < count($list)){
    if($list[$i] != '.') {
      if($list[$i] != '..') {
        echo "<li><a href=\"index.php?id=$list[$i]\">$list[$i]</a></li>\n";
      }
    }
    $i = $i + 1;
  }
}
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>
      <?php
      print_title();
      ?>
    </title>
  </head>
  <body>
    <h1><a href="index.php">WEB</a></h1>
    <ol>
      <?php
      print_list();
      ?>
    </ol>
    <a href="create.php">create</a>
    <h2>
      <?php
      print_title();
      ?>
    </h2>
    <?php
    print_description();
     ?>
  </body>
</html>
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기