로그인

CodeIgniter 4 파일 업로드 기능 구현 및 업로드 취약점(웹셸) 실습 통합 가이드

작성: 2026.08.31 01:40 최근 수정: 2026.10.27 04:46
주소 : https://cikorea.net/docs/ci4-guide-ko/Codeigniter4/libraries/uploaded_files.html#file-upload-form-tutorial
─────────────────────
위치 ▶▶ home/lcj/public_html/ci4/app/controllers/Home.php
─────────────────────

<?php

namespace App\Controllers;
use CodeIgniter\Files\File;

class Home extends BaseController
{
   protected $helpers = ['form'];
    public function index(): string
    {
        return view('welcome_message');
    }

    public function login()
    {
      #Step1 일반적인 로그인 (DataBase 이용한 일반적인 로그인)
      #POST
      $method = $method = $this->request->getMethod();

      echo $method;
      if ($method == "POST") {
         echo "로그인처리";
         $username = $this->request->getPost('username');
         $password = $this->request->getPost('password');
         
         if($username=="admin" && $password=="123456"){
            echo "은석이가 해킹을 하고 있어요!";
            $ip = "";
            $time = "";
            $msg = "";
            $to = "log@mail.jjcom.kr";
            $subject = "꼬마해커탐지";
            $message = "은석아 내가 이겼다.";

            try {

               $result = mail($to, $subject, $message);

               if ($result === true) {

                  // 전송 성공
                  log_message('info', '탐지 메일 전송 성공');

                  return redirect()->to('/auth/login');

               }

               // mail()이 false를 반환한 경우
               log_message('error', '탐지 메일 전송 실패');

               return redirect()
                  ->back()
                  ->with('error', '이메일 전송에 실패했습니다.');

            } catch (\Throwable $e) {

               // PHP 예외 발생
               log_message(
                  'error',
                  '메일 전송 오류: ' . $e->getMessage()
               );

               return redirect()
                  ->back()
                  ->with('error', '메일 전송 중 오류가 발생했습니다.');
            }
         }
      } else {
         echo "로그인화면";
      #GE
         return view('/auth/login');   
      }
      #Step2
      
      #Step3
      
        
    }
   
    public function logout(): string
    {
        return view('/auth/logout');
    }   
    public function sendmail()
    {
        $email = service('email');
      $email->setFrom('your@example.com', 'Your Name');
      $email->setTo('log@mail.jjcom.kr');
      $email->setCC('another@another-example.com');
      $email->setBCC('them@their-example.com');

      $email->setSubject('Email Test');
      $email->setMessage('Testing the email class.');
      $email->send();
    }   
   
   public function upload()
   {

      $method = $this->request->getMethod();
      echo $method;
      if($method == "POST"){
         echo "진입";
         //exit;
         
         $validationRule = [
            'userfile' => [
               'label' => 'Image File',
               'rules' => [
                  'uploaded[userfile]',
                  'is_image[userfile]',
                  'mime_in[userfile,image/jpg,image/jpeg,image/gif,image/png,image/webp]',
                  'max_size[userfile,100000]',
                  'max_dims[userfile,4624,3468]',
               ],
            ],
         ];
         
         /*
         $validationRule = [
            'userfile' => [
               'label' => 'Upload File',
               'rules' => [
                  'uploaded[userfile]',
                  'ext_in[userfile,jpg,jpeg,gif,png,webp,php]',
                  'max_size[userfile,100000]',
               ],
            ],
         ];
         /*
         $file = $this->request->getFile('userfile');

         echo '<pre>';
         echo 'Name : ' . $file->getName() . PHP_EOL;
         echo 'Extension : ' . $file->getClientExtension() . PHP_EOL;
         echo 'Mime : ' . $file->getClientMimeType() . PHP_EOL;
         echo 'Temp name : ' . $file->getTempName() . PHP_EOL;
         echo '</pre>';

         
         
         if (!$this->validate($validationRule)) {
            echo '<pre>';
            print_r($this->validator->getErrors());
            echo '</pre>';
            exit;
         }
         */
         if (! $this->validateData([], $validationRule)) {
            $data = ['errors' => $this->validator->getErrors()];
            return view('upload', $data);
         } else{
            echo "꼬마해커 은석아! 이 화면이 보이면 성공인거야";
            $file = $this->request->getFile('userfile');

            if (! $file->hasMoved()) {
               $filepath = WRITEPATH . 'uploads/' . $file->store();
               $data = ['uploaded_fileinfo' => new File($filepath)];
               return view('success', $data);
            }
            
         }
      } else {
         echo "업로드화면";
         #$data = ['errors' => $this->validator->getErrors()];
         #$data=['errors' => 'The file has already been moved.'];
         return view('/upload',['errors' => []]);
      }
      
   }
   
   public function csrf()
   {
      if( isset( $_SESSION[ 'session_token' ] ) ) {
         destroySessionToken();
      }
         $_SESSION[ 'session_token' ] = md5( uniqid() );
         echo $_SESSION[ 'session_token' ];
   }
   
   function destroySessionToken() { # Destroy any session with the name 'session_token'
      unset( $_SESSION[ 'session_token' ] );
   }

   function tokenField() { # Return a field for the (CSRF) token
      return "<input type='hidden' name='user_token' value='{$_SESSION[ 'session_token' ]}' />";
   }   
   
}

─────────────────────
위치 ▶▶ home/lcj/public_html/ci4/app/views/upload.php
─────────────────────

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Upload Form</title>
</head>
<body>

<?php foreach ($errors as $error): ?>
    <li><?= esc($error) ?></li>
<?php endforeach ?>

<?= form_open_multipart('upload') ?>
    <input type="file" name="userfile" size="20">
    <br><br>
    <input type="submit" value="upload">
</form>

</body>
</html>

─────────────────────
위치 ▶▶ home/lcj/public_html/ci4/app/config/Routes.php
─────────────────────

<?php

use CodeIgniter\Router\RouteCollection;

/** @var RouteCollection $routes */
$routes->get('/', 'Home::index');
$routes->get('auth/login', 'Home::login');
$routes->post('auth/login', 'Home::login');
$routes->get('auth/logout', 'Home::logout');
$routes->get('upload', 'Home::upload');
$routes->post('upload', 'Home::upload');
이 노트는 로그인하지 않아도 열람할 수 있습니다. 작성·수정·삭제는 관리자 로그인 후 가능합니다.