PHP cURL 응답에서 헤더 가져오기

PHP를 처음 사용합니다. php curl POST 요청을 보낸 후 응답에서 헤더를 얻으려고 합니다. 클라이언트는 서버에 요청을 보내고 서버는 헤더와 함께 응답을 다시 보냅니다. 제가 POST 요청을 보낸 방법은 다음과 같습니다.

   $client = curl_init($url);  
   curl_setopt($client, CURLOPT_CUSTOMREQUEST, "POST");
   curl_setopt($client, CURLOPT_POSTFIELDS, $data_string);
   curl_setopt($client, CURLOPT_HEADER, 1);
   $response = curl_exec($client);
   var_dump($response);

다음은 브라우저에서 받은 서버의 헤더 응답입니다.

HTTP/1.1 200 OK 
Date: Wed, 01 Feb 2017 11:40:59 GMT 
Authorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2Vycy9CYW9CaW5oMTEwMiIsIm5hbWUiOiJhZG1pbiIsInBhc3N3b3JkIjoiMTIzNCJ9.kIGghbKQtMowjUZ6g62KirdfDUA_HtmW-wjqc3ROXjc Content-Type: text/html;charset=utf-8 Transfer-Encoding: chunked Server: Jetty(9.3.6.v20151106) 

헤더에서 인증 부분을 추출하려면 어떻게 해야 하나요? 쿠키에 저장해야 합니다.

해결책

모든 헤더를 배열로 변환합니다.

// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//enable headers
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);

$headers = [];
$output = rtrim($output);
$data = explode("\n",$output);
$headers['status'] = $data[0];
array_shift($data);

foreach($data as $part){

    //some headers will contain ":" character (Location for example), and the part after ":" will be lost, Thanks to @Emanuele
    $middle = explode(":",$part,2);

    //Supress warning message if $middle[1] does not exist, Thanks to @crayons
    if ( !isset($middle[1]) ) { $middle[1] = null; }

    $headers[trim($middle[0])] = trim($middle[1]);
}

// Print all headers as array
echo "<pre>";
print_r($headers);
echo "</pre>";
해설 (6)

첫 번째 답변의 경우 코드에 유의하세요:

$middle=explode(":",$part);

와 같이 :가 포함된 문자열 데이터는 잘못된 결과를 생성합니다:

Sat, 14 Jan 2017 01:10:01 GMT

배열을 만들기 위해 필드를 분할하는 올바른 코드는 다음과 같습니다:

$middle=explode(":",$part,2);
해설 (0)

컬 요청에 다음 코드를 포함하기만 하면 됩니다.

curl_setopt($curl_exec, CURLOPT_HEADER, true); 
curl_setopt($curl_exec, CURLOPT_NOBODY, true);

컬 실행 후 $header_data= curl_getinfo($curl_exec);를 사용하면 됩니다.

그러면 모든 헤더를 얻을 수 있습니다.

print_r($header_data);

를 사용하거나 shell_exec

echo shell_exec("curl -I http://example.com ");
해설 (2)