[Normaltic's 취업반 과제] 게시글 파일 이름 띄우기

2024. 5. 15. 16:34정보보안 및 해킹/Normaltic's 취업반 과제

해당 기능은 불과 몇 년 전까지는 보안 이슈로 불가능했던 기능인 것 같다.

그럼에도 불구하고 몇 몇 개발자들은 꼼수를 부려 외부 플러그인으로 이용했던 모양인데...

심지어 어떤 사람은 해당 질문을 한 초보 개발자에게 그게 질문이냐고 비난하는 댓글까지 있었다..

 

이미지가 없는 게시글입니다.
이미지가 없는 상태의 DB입니다.
이미지가 없을 때에는 수정하기를 누르면 선택된 파일 없음 이라고 표시됩니다.
보안 이슈로 인해 fakepath가 추가되었습니다.
이미지를 추가합니다.
이미지 경로가 들어갔습니다.
이미지가 잘 도출됩니다.
이미지가 추가된 이후 수정하기를 누르면 이미지 경로를 도출합니다.

write_board.php

게시글을 맨 처음 등록하는 부분입니다.

해당 영역에서는 이미지만 넣기를 원했기 때문에 넣는 파일은 이미지로 제한해 주는것을 추가해줍니다.

보안을 위해 fakepath를 추가해줍니다.

[생략]

<input type="file" name="reviewimage" accept="image/*" onchange="alert(this.value)"><br>

[생략]

edit_contents.php

게시글을 수정하는 부분입니다.

등록하는것과 마찬가지로 이미지만 받도록 하고, 보안을 위해 fakepath를 추가합니다.

js로 file을 input하는 부분에서

const fileInput = document.querySelector('input[type="file"]');

새로운 File Object를 생성하고

const myFileContent = ['File Content'];

이름을 지정하고 - DB에 이름이 이미 있으니 그걸 가져다 써줍니다

const myFileName  = "<?php echo $sql_row['review_image']?>";

데이터 변환하는 객체를 생성하여

const dataTransfer = new DataTransfer();

추가해줍니다.

dataTransfer.items.add(myFile);
    const fileList = dataTransfer.files;
    fileInput.files = fileList;

FULL CODE

[생략]

<input type="file" name="row_review_image" value="" accept="image/*" onchange="alert(this.value)"/>
  
  
  <script>
   
    // Get a reference to our file input
    const fileInput = document.querySelector('input[type="file"]');

    const myFileContent = ['File Content'];
    const myFileName  = "<?php echo $sql_row['review_image']?>";
    const myFile = new File(myFileContent, myFileName);
    const dataTransfer = new DataTransfer();
    dataTransfer.items.add(myFile);
    const fileList = dataTransfer.files;
    fileInput.files = fileList;

</script>

[생략]

 

 

ref. https://pqina.nl/blog/set-value-to-file-input/

 

How To Set The Value Of A File Input

It’s always been impossible to set the value of a file input element with JavaScript, but this has changed last year and it’s now broadly supported, let’s see how it’s done.

pqina.nl

https://hianna.tistory.com/346

 

[HTML] input type='file' 속성 알아보기 ( 파일 입력 )

웹페이지에서 사용자의 로컬 파일을 입력받기 위해서는 다음과 같이 input 태그의 type속성을 file로 지정하는 방법을 사용합니다. See the Pen read file by anna (@hianna) on CodePen. 여기에서는 input의 type을 '

hianna.tistory.com

https://www.w3schools.com/php/php_file_upload.asp

 

PHP File Upload

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

https://dev.to/code_rabbi/programmatically-setting-file-inputs-in-javascript-2p7i

 

Programmatically Setting File Inputs in JavaScript

Setting the value of a text or number input is as simple as doing const input =...

dev.to