[php] PHP에서 API 호출을 위한 사용자 정의 헤더 설정

PHP에서 API를 호출할 때는 때로는 사용자 정의 헤더를 설정해야 할 수 있습니다. 이를 통해 특정한 요구사항에 맞게 HTTP 요청을 보낼 수 있습니다. PHP에서는 stream_context_create 함수를 사용하여 사용자 정의 헤더를 설정할 수 있습니다.

사용자 정의 헤더 설정하기

$url = 'https://api.example.com/data';
$data = array('key1' => 'value1', 'key2' => 'value2');

$options = array(
  'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n" .
                 "Authorization: Bearer your_access_token\r\n",
    'method'  => 'POST',
    'content' => http_build_query($data),
  ),
);

$context  = stream_context_create($options);
$response = file_get_contents($url, false, $context);

위 예시에서는 stream_context_create 함수를 사용하여 HTTP 요청을 보내는데 필요한 사용자 정의 헤더를 설정했습니다. Content-typeAuthorization 헤더를 추가하여 API 요청에 필요한 정보를 포함시켰습니다.

결론

PHP에서 API를 호출할 때 사용자 정의 헤더를 설정하는 방법을 살펴보았습니다. 이를 통해 API 요청 시 특정한 헤더를 포함시키고 싶은 경우 유용하게 활용할 수 있습니다.

참고문헌: