[php] PHP를 사용한 파일 업로드와 파일 다운로드

파일 업로드

파일 업로드는 PHP에서 간단하게 처리할 수 있습니다. 먼저 HTML form을 사용하여 파일을 업로드할 수 있는 화면을 만들어줍니다.

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

이제 PHP 파일인 upload.php를 작성하여 이 업로드를 처리합니다.

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

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

위 코드에서는 move_uploaded_file() 함수를 사용하여 업로드된 파일을 지정된 디렉토리로 이동시킵니다.


파일 다운로드

이제 파일을 업로드했다면, 해당 파일을 사용자에게 제공하기 위해 파일 다운로드를 구현할 수 있습니다.

다운로드 링크를 생성하는 HTML 코드는 다음과 같습니다.

<a href="download.php?file=example.pdf">Download example.pdf</a>

다음으로, download.php 파일을 만들어서 파일을 다운로드할 수 있도록 합니다.

<?php
$file = $_GET['file'];
$filepath = 'uploads/' . $file;

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
readfile($filepath);
exit;
?>

위 코드에서는 readfile() 함수를 사용하여 서버에 저장된 파일을 읽어와 클라이언트로 전송합니다.

결론

PHP를 사용하여 파일 업로드와 다운로드를 구현하는 것은 상당히 간단합니다. 위의 예시를 따라하면 사용자가 파일을 업로드하고 다운로드할 수 있는 기능을 간단하게 구현할 수 있습니다.

PHP 파일 업로드 및 다운로드 관련 문서를 참고하시기 바랍니다.