[php] PHP를 사용한 파일 업로드와 콘텐츠 디스포지션 설정

파일 업로드는 웹 애플리케이션에서 매우 일반적이며, PHP에서는 이를 처리하기 위한 다양한 내장 함수와 기능을 제공합니다. 파일 업로드를 안전하게 처리하고, 콘텐츠 디스포지션을 올바르게 설정하여 보안을 강화할 수 있습니다. 이번 포스트에서는 PHP를 사용하여 파일 업로드를 처리하고, 콘텐츠 디스포지션을 설정하는 방법에 대해 알아보겠습니다.

파일 업로드

PHP에서 파일 업로드를 처리하기 위해서는 $_FILES 슈퍼글로벌 변수를 사용합니다. 이 변수는 HTTP POST로 업로드된 파일의 정보를 담고 있습니다.

예를 들어, 다음은 파일 업로드 폼과 PHP에서 파일을 처리하는 예제입니다.

파일 업로드 폼

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="Upload">
</form>

PHP 파일 처리

<?php
$targetDirectory = "uploads/";
$targetFile = $targetDirectory . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
    echo "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>

위의 예제에서는 먼저 업로드할 파일을 지정한 디렉토리에 이동시킵니다. 이때, move_uploaded_file 함수를 사용하여 올바른 디렉토리로 파일을 이동시킵니다. 또한, 업로드된 파일의 이름은 name 키를 통해 접근할 수 있습니다.

콘텐츠 디스포지션 설정

콘텐츠 디스포지션 헤더는 브라우저가 서버로부터 수신한 콘텐츠를 어떻게 처리할지를 지정하는 데 사용됩니다. 파일 다운로드 중에 콘텐츠 디스포지션 헤더를 사용하여 파일의 이름 및 다운로드 옵션을 설정할 수 있습니다.

예를 들어, 다음은 PHP를 사용하여 파일 다운로드 중 콘텐츠 디스포지션을 설정하는 예제입니다.

<?php
$filePath = "path/to/file";
$fileName = "example.txt";

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
?>

Content-Disposition 헤더를 사용하여 브라우저가 파일을 다운로드하도록 요청할 수 있습니다. 또한, attachmentfilename 속성을 이용하여 파일 이름을 지정할 수 있습니다.

이렇게 함으로써, PHP를 사용하여 파일을 안전하게 업로드하고, 콘텐츠 디스포지션 헤더를 설정하여 파일 다운로드를 보다 안전하게 제어할 수 있습니다.