개요
컨텍스트 매개변수(Context Parameters)는 파일 시스템과 https://, ftp:// 등 다양한 스트림 래퍼(stream wrapper)에 대한 접근 방식을 세부적으로 사용자 정의할 수 있게 해주는 기능입니다. PHP에서는 stream_context_set_params() 함수를 사용하여 생성된 스트림이나 컨텍스트에 이러한 매개변수를 설정할 수 있습니다.
문법
stream_context_set_params ( resource $stream_or_context , array $params ) : bool
매개변수 설명
$stream_or_context — PHP가 지원하는 모든 스트림, 래퍼(wrapper), 컨텍스트 리소스를 지정할 수 있습니다.
$params — 설정할 매개변수를 담은 배열로, 반드시 다음과 같은 연관 배열(associative array) 형태여야 합니다.
$params['paramname'] = "paramvalue";
주요 컨텍스트 매개변수
notification
스트림 작업 중 알림(notification)이 발생할 때마다 호출되는 사용자 정의 콜백 함수입니다. 진행 상황 추적이나 오류 감지에 유용하며, https:// 및 ftp:// 스트림 래퍼에서만 지원됩니다.
알림 콜백 함수는 다음과 같은 시그니처(signature)를 가져야 합니다.
stream_notification_callback (
int $notification_code ,
int $severity ,
string $message ,
int $message_code ,
int $bytes_transferred ,
int $bytes_max
) : void
- $notification_code — 발생한 알림의 종류를 나타내는 코드 (예: STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_PROGRESS 등)
- $severity — 알림의 심각도 수준 (STREAM_NOTIFY_SEVERITY_INFO, WARN, ERR)
- $message — 알림과 관련된 메시지 문자열
- $message_code — 메시지와 연관된 추가 코드
- $bytes_transferred — 현재까지 전송된 바이트 수
- $bytes_max — 전송해야 할 전체 바이트 수
options
현재 사용 중인 컨텍스트 또는 래퍼에 해당하는 지원 옵션들의 배열입니다. 타임아웃, 프록시, 헤더 설정 등 래퍼별 세부 동작을 제어할 때 사용합니다.
사용 예제
다음 예제는 컨텍스트를 생성하고 알림 콜백을 등록한 후, 원격 파일을 읽어오는 과정에서 알림을 받는 방법을 보여줍니다.
<?php
// 알림 콜백 함수 정의
function stream_notification_callback(
$notification_code, $severity, $message,
$message_code, $bytes_transferred, $bytes_max
) {
switch ($notification_code) {
case STREAM_NOTIFY_CONNECT:
echo "연결됨...\n";
break;
case STREAM_NOTIFY_PROGRESS:
echo "진행률: {$bytes_transferred} / {$bytes_max} bytes\n";
break;
}
}
// 컨텍스트 생성 후 매개변수 설정
$ctx = stream_context_create();
stream_context_set_params($ctx, array("notification" => "stream_notification_callback"));
// 컨텍스트를 적용하여 원격 데이터 읽기
file_get_contents("https://php.net/contact", false, $ctx);
?>
정리
stream_context_set_params() 함수는 스트림 동작을 세밀하게 제어할 수 있는 핵심 도구입니다. 특히 대용량 파일 다운로드 시 진행 상황을 모니터링하거나, 네트워크 요청의 상태 변화를 실시간으로 처리해야 할 때 notification 콜백을 활용하면 매우 유용합니다.