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

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

생활코딩 유튜브

 

생활코딩

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

www.youtube.com

생활코딩 사이트

 

생활코딩

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

opentutorials.org

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

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

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


#0.

이번 시간에는 코드의 중복을 제거하는 리펙토링 과정을 거치고자 한다.

프로그렘에서 코드를 재사용하기 좋도록 잘 정리정돈하고자 한다.

lib이라는 dir를 만들어서 재사용하기 좋은 코드를 모아보자.

lib/print.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;
  }
}
?>

그렇다면 index.php에서 lib/print.php의 내용을 사용할 수 있도록 require하는 과정을 거쳐야 한다.

<?php
require_once('lib/print.php');
?>

비단 이 과정은 index.php 뿐만 아니라,

create.php, update.php에서도 동일하게 적용해줄 수 있다.

이러한 과정을 거친다면 print.php를 수정하는 것만으로 모든 웹페이지를 수정할 수 있다.

마찬가지로 중복되는 모든 코드를 수정하여 레이아웃을 만들어 줄 수 있다.

view/top.php

<?php
require_once('lib/print.php');
?>
<!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>

view/bottom.php

</body>
</html>

index.php

<?php
require_once('lib/print.php');
require_once('view/top.php');
?>
    <a href="create.php">create</a>
    <?php if(isset($_GET['id'])) { ?>
      <a href="update.php?id=<?=$_GET['id']?>">update</a>
      <form action="delete_process.php" method="post">
        <input type="hidden" name="id" value="<?=$_GET['id']?>">
        <input type="submit" value="delete">
      </form>
    <?php } ?>
    <h2>
      <?php
      print_title();
      ?>
    </h2>
    <?php
    print_description();
     ?>
<?php
require_once('view/bottom.php');
?>

create.php

<?php
require('lib/print.php');
require('view/top.php');
?>
    <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>
<?php
require('view/bottom.php');
?>

update.php

<?php
require('lib/print.php');
require('view/top.php');
?>
    <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>
<?php
require('view/bottom.php');
?>

#1.

현재 우리 코드의 문제점을 알아보자.

만약 우리가 create하고자 하는 내용에 <script> 태그를 활용하여 내용을 채우게 된다면,

그 내용 그대로 JavaScript가 실행되는 것을 확인할 수 있다.

이를 해결하기 위해 php의 htmlspecialchars함수를 통해 스크립트가 아닌 텍스트로 다룰 수 있다.

 

PHP: htmlspecialchars - Manual

if your goal is just to protect your page from Cross Site Scripting (XSS) attack, or just to show HTML tags on a web page (showing on the page, for example), then using htmlspecialchars() is good enough and better than using htmlentities().  A minor point

www.php.net

htmlspecialchars ( string $string [, int $flags=ENT_COMPAT [, string | null $encoding =null [, bool $double_encode=true ]]]) : string

이 함수를 통해서 HTML 을 그대로 모든 문자열로 출력할 수 있게 된다.

조금 더 자세하게 말하자면 HTML에서 인식하는 코드들을 엔티티로 바꾸어서 표현하게 된다.

lib/print.php

<?php
function print_title(){
  if(isset($_GET['id'])){
    echo htmlspecialchars($_GET['id']);
  } else {
    echo "Welcome";
  }
}
function print_description(){
  if(isset($_GET['id'])){
    echo htmlspecialchars(file_get_contents("data/".$_GET['id']));
  } else {
    echo "Hello, PHP";
  }
}
function print_list(){
  $list = scandir('./data');
  $i = 0;
  while($i < count($list)){
    $title = htmlspecialchars($list[$i]);
    if($list[$i] != '.') {
      if($list[$i] != '..') {
        echo "<li><a href=\"index.php?id=$title\">$title</a></li>\n";
      }
    }
    $i = $i + 1;
  }
}
?>

#2.

우리가 사용하고자 하는 파일의 경로를 숨기려면 어떻게 해야할까?

basename함수를 사용하여 이를 해결할 수 있다.

 

PHP: basename - Manual

It might be useful to have a version of the function basename working with arrays too.

basename함수는 파일의 경로에서 파일 명만 추출해주는 기능으로 동작한다.

lib/print.php

<?php
function print_title(){
  if(isset($_GET['id'])){
    echo htmlspecialchars($_GET['id']);
  } else {
    echo "Welcome";
  }
}
function print_description(){
  if(isset($_GET['id'])){
    $basename = basename($_GET['id']);
    echo htmlspecialchars(file_get_contents("data/".$basename));
  } else {
    echo "Hello, PHP";
  }
}
function print_list(){
  $list = scandir('./data');
  $i = 0;
  while($i < count($list)){
    $title = htmlspecialchars($list[$i]);
    if($list[$i] != '.') {
      if($list[$i] != '..') {
        echo "<li><a href=\"index.php?id=$title\">$title</a></li>\n";
      }
    }
    $i = $i + 1;
  }
}
?>

delete.php

<?php
    unlink('data/'.basename($_POST['id']));
    header('Location: /index.php');
?>

#3-0.

API는 애플리케이션을 만들기 위해서 기반이 되는 시스템(웹브라우저, PHP)이 제공하는 기능을 부품으로 사용해야 합니다. 이런 기능을 사용하기 위해서 호출하는 명령어를 API라고 합니다. PHP에서는 주로 함수의 형태로 API가 제공됩니다. 여기서는 API가 무엇인지 설명드리고, 어떤 방법으로 공부하면 좋을지는 필자의 사견을 담아서 이야기해봤습니다. 

  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기