PHP POST 데이터가 안 넘어오는 문제 해결하기

프리터코더·2025년 5월 25일

php 문제 해결

목록 보기
23/79

POST 요청으로 전송한 데이터가 PHP에서 받아지지 않는 문제의 원인과 해결 방법을 알아보겠습니다.

주요 증상

var_dump($_POST); // array(0) { }
var_dump($_REQUEST); // 빈 배열 또는 일부 데이터만 존재

원인 분석

  1. Content-Type 불일치: 잘못된 헤더 설정
  2. 데이터 크기 초과: PHP 설정 제한 초과
  3. HTTP 메서드 오류: GET으로 전송하거나 메서드 불일치
  4. JSON 데이터: application/json으로 전송된 데이터

해결책

1. 기본 POST 데이터 확인

// POST 데이터 디버깅
echo "REQUEST_METHOD: " . $_SERVER['REQUEST_METHOD'] . "\n";
echo "CONTENT_TYPE: " . ($_SERVER['CONTENT_TYPE'] ?? 'not set') . "\n";
echo "CONTENT_LENGTH: " . ($_SERVER['CONTENT_LENGTH'] ?? 'not set') . "\n";

echo "\n=== \$_POST ===\n";
var_dump($_POST);

echo "\n=== Raw Input ===\n";
$rawInput = file_get_contents('php://input');
echo $rawInput;

echo "\n=== All Headers ===\n";
var_dump(getallheaders());

2. JSON 데이터 처리

function getPostData() {
    $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
    
    // JSON 데이터인 경우
    if (strpos($contentType, 'application/json') !== false) {
        $rawInput = file_get_contents('php://input');
        $data = json_decode($rawInput, true);
        
        if (json_last_error() === JSON_ERROR_NONE) {
            return $data;
        } else {
            throw new Exception('JSON 파싱 오류: ' . json_last_error_msg());
        }
    }
    
    // 일반 POST 데이터
    return $_POST;
}

// 사용법
try {
    $postData = getPostData();
    var_dump($postData);
} catch (Exception $e) {
    echo "오류: " . $e->getMessage();
}

3. 파일 업로드 포함 데이터

function handleMultipartData() {
    $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
    
    if (strpos($contentType, 'multipart/form-data') !== false) {
        return [
            'post' => $_POST,
            'files' => $_FILES
        ];
    }
    
    return $_POST;
}

// 파일 업로드 확인
if (!empty($_FILES)) {
    foreach ($_FILES as $key => $file) {
        echo "파일 필드: $key\n";
        echo "파일명: " . $file['name'] . "\n";
        echo "크기: " . $file['size'] . " bytes\n";
        echo "오류: " . $file['error'] . "\n";
    }
}

4. PHP 설정 확인 및 조정

// 현재 설정 확인
echo "post_max_size: " . ini_get('post_max_size') . "\n";
echo "upload_max_filesize: " . ini_get('upload_max_filesize') . "\n";
echo "max_input_vars: " . ini_get('max_input_vars') . "\n";
echo "max_execution_time: " . ini_get('max_execution_time') . "\n";

// 설정 조정 (필요시)
ini_set('post_max_size', '50M');
ini_set('upload_max_filesize', '50M');
ini_set('max_input_vars', 3000);

5. 범용 POST 데이터 핸들러

class PostDataHandler {
    public static function getData() {
        $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
        
        if ($method !== 'POST') {
            return [];
        }
        
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        
        // JSON 데이터
        if (strpos($contentType, 'application/json') !== false) {
            return self::parseJson();
        }
        
        // XML 데이터
        if (strpos($contentType, 'application/xml') !== false) {
            return self::parseXml();
        }
        
        // 일반 form 데이터
        return $_POST;
    }
    
    private static function parseJson() {
        $input = file_get_contents('php://input');
        $data = json_decode($input, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception('Invalid JSON: ' . json_last_error_msg());
        }
        
        return $data ?? [];
    }
    
    private static function parseXml() {
        $input = file_get_contents('php://input');
        $xml = simplexml_load_string($input);
        
        if ($xml === false) {
            throw new Exception('Invalid XML');
        }
        
        return json_decode(json_encode($xml), true);
    }
}

6. 클라이언트 측 확인

<!-- 올바른 HTML 폼 -->
<form method="POST" action="handler.php" enctype="application/x-www-form-urlencoded">
    <input type="text" name="username" value="test">
    <input type="email" name="email" value="test@example.com">
    <button type="submit">전송</button>
</form>

<!-- 파일 업로드 포함 -->
<form method="POST" action="upload.php" enctype="multipart/form-data">
    <input type="file" name="upload_file">
    <input type="text" name="description">
    <button type="submit">업로드</button>
</form>
// JavaScript AJAX 요청
// JSON 전송
fetch('/api/endpoint', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
        username: 'test',
        email: 'test@example.com'
    })
});

// Form 데이터 전송
const formData = new FormData();
formData.append('username', 'test');
formData.append('email', 'test@example.com');

fetch('/api/endpoint', {
    method: 'POST',
    body: formData
});

디버깅 체크리스트

  1. HTTP 메서드 확인: $_SERVER['REQUEST_METHOD']
  2. Content-Type 확인: $_SERVER['CONTENT_TYPE']
  3. 데이터 크기 확인: $_SERVER['CONTENT_LENGTH']
  4. Raw 입력 확인: file_get_contents('php://input')
  5. PHP 설정 확인: post_max_size, max_input_vars

예방법

  • 적절한 Content-Type 헤더 설정
  • PHP 설정값 사전 확인
  • 클라이언트-서버 간 데이터 형식 통일
  • 에러 로깅 및 모니터링 구현
profile
일용직 개발자. freetercoder@gmail.com

0개의 댓글