[php] PHP를 사용한 파일 업로드와 파일 업로드 REST API 구현

파일 업로드는 웹 애플리케이션에서 자주 사용되는 기능입니다. PHP와 REST API를 사용하여 파일을 업로드하고 관리하는 방법에 대해 알아보겠습니다.

1. PHP를 사용한 파일 업로드

PHP를 사용하여 파일을 업로드하려면 다음과 같은 단계가 필요합니다.

파일 업로드 폼 생성

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

업로드된 파일 처리

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
echo "파일이 업로드되었습니다.";
?>

2. 파일 업로드 REST API 구현

파일 업로드를 위한 REST API를 구현하려면 다음과 같은 단계를 따를 수 있습니다.

POST 메서드를 사용한 파일 업로드

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $file_name = $_SERVER['HTTP_X_FILE_NAME'];
    file_put_contents('uploads/' . $file_name, $input);
    echo "파일이 업로드되었습니다.";
}
?>

cURL을 이용한 파일 업로드

curl -X POST -H 'Content-Type: application/octet-stream' -H 'X-File-Name: example.jpg' --data-binary '@example.jpg' http://example.com/upload

마치며

이제 PHP를 사용한 파일 업로드와 REST API를 이용한 파일 업로드에 대해 알아보았습니다. 파일 업로드는 보안에 주의해야 하며, 업로드된 파일에 대한 적절한 검증과 처리가 필요합니다.

참고문헌