PHP Curl을 이용해서 Response header 값을 가져오기
이번에 다음커뮤니케이션 시스템과 회원연동을 할 일이 있었다.
다음커뮤니케이션은 로그인인증시 결과값이 헤더에 나타난다.
많은 문서들이 curl_getinfo 를 사용하도록 하고 있지만 이것으로는 response 헤더값을 얻을 수 없다.
curl_getinfo 는 request에 대한 헤더이지 response 의 헤더가 아니다.
참고로 아래의 구문을 추가하고, curl_getinfo를 하면 request header 를 살펴볼 수 있다.
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
따라서 response header 를 처리하는 함수를 만들었다.
request로 raw response header를 받고 본문을 잘라내어 버린다음 헤더내용만 파싱하여 배열로 추출한다.
function make_curl($url, $post_field){ $request_timeout = 10; // 1 second timeout $request = curl_init(); curl_setopt($request, CURLOPT_URL, $url); curl_setopt($request, CURLOPT_RETURNTRANSFER, true); curl_setopt($request, CURLOPT_FOLLOWLOCATION, true); curl_setopt($request, CURLOPT_TIMEOUT, $request_timeout); curl_setopt($request, CURLOPT_CONNECTTIMEOUT, $request_timeout); curl_setopt($request, CURLOPT_COOKIEJAR, 'curl_cookie/cookie_'.$_SERVER['REMOTE_ADDR'].'_.txt'); curl_setopt($request, CURLOPT_COOKIEFILE, 'curl_cookie/cookie_'.$_SERVER['REMOTE_ADDR'].'_.txt'); curl_setopt($request, CURLOPT_POST, 1); curl_setopt($request, CURLOPT_HEADER, 1);//헤더를 포함한다. curl_setopt($request, CURLOPT_POSTFIELDS, $post_field); curl_setopt($request, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded', 'Connection: Close')); $result = curl_exec($request); return $result; }
function get_http_header_as_array($rawheader){ $header_array = array(); $header_rows = explode("\n",$rawheader); for($i=0;$i<count($header_rows);$i++){ $fields = explode(":",$header_rows[$i]); if($i != 0 && !isset($fields[1])){//carriage return bug fix. if(substr($fields[0], 0, 1) == "\t"){ end($header_array); $header_array[key($header_array)] .= "\r\n\t".trim($fields[0]); } else{ end($header_array); $header_array[key($header_array)] .= trim($fields[0]); } } else{ $field_title = trim($fields[0]); if (!isset($header_array[$field_title])){ $header_array[$field_title]=trim($fields[1]); } else if(is_array($header_array[$field_title])){ $header_array[$field_title] = array_merge($header_array[$fields[0]], array(trim($fields[1]))); } else{ $header_array[$field_title] = array_merge(array($header_array[$fields[0]]), array(trim($fields[1]))); } } } return $header_array; }
if ($curl_result !== '') { $split_result = split("\r\n\r\n", $curl_result, 2); $header = $split_result[0]; //$body = $split_result[1]; $header_arr = get_http_header_as_array($header); }
header 파싱 예시