2014-11-18 1 views
1

저는 CURL이 없으므로 PHP의 stream_get_contents 메커니즘을 사용하여 요청을하려고합니다. 이 요청은 로컬에서 제대로 작동하지만 원격 서버에 배포하면 모든 헤더가 전송되지 않습니다. 다음은 PHP 조각입니다 :stream_get_contents를 사용할 때 인증 헤더가 사라지는 이유는 무엇입니까?

<?php 
$context = stream_context_create(array(
    'http' => array(
     'method' => 'POST', 
     'header' => array(
      'Content-type: application/json', 
      'Authorization: Basic '.base64_encode('username:secret'), 
     ), 
     'content' => json_encode(array(
      'key' => 'value', 
     )), 
    ) 
)); 
file_get_contents('http://requestb.in/xxxxxx', false, $context); 
?> 

이가 내 로컬 컴퓨터에서 실행되는 서버에 의해 수신 나는 다음과 같은 헤더를 참조하십시오 여기

Via: 1.1 vegur 
Authorization: Basic dXNlcm5hbWU6c2VjcmV0 
Host: requestb.in 
Content-Length: 70 
Total-Route-Time: 0 
Content-Type: application/json 
X-Request-Id: a2cf10d8-a82a-4302-897f-3f40daa22028 
Connect-Time: 1 
Connection: close 

... 내가 실행할 때 내가 무엇을 얻을 원격 서버의 스 니펫. 내 POST 요청의 페이로드를 수정했기 때문에

User-Agent: PHP/5.2.17 
Host: requestb.in 
Via: 1.1 vegur 
X-Request-Id: 14e7af5f-39aa-474a-8d1a-af992997d0ef 
Content-Length: 70 
Total-Route-Time: 0 
Content-Type: application/x-www-form-urlencoded 
Accept: */* 
Connect-Time: 7 
Connection: close 

내용 길이는 다르지만 당신이 볼 수 있듯이, 나는 두 번째 시나리오에서 Authorisation 헤더를 얻을 수 있고, Content-Type 헤더도 변경되었습니다.

나는 정말 이걸 잃어 버렸고,이 독특한 행동에 대한 설명을 찾지 못했습니다. (저는 문제 해결을 돕기 위해 RequestBin을 사용하고 있습니다.)

+0

두 시나리오 모두에서 PHP를 통해 실행하고 있습니까? –

+0

CLI를 통해 실행하지 않을 것입니다 (이것이 의미하는 것이면), 아파치에서 실행중인 PHP 스크립트입니다. –

답변

0

컨텍스트 배열의 'header' 키는 문자열이어야합니다. PHP는 "-curlwrappers --with"플래그를 사용하여 컴파일 된 경우 PHP docs here

$method = 'GET'; 
$contextOptions = array(
    'http' => array(
     'method' => $method, 
     'header' => array(
      'X-Forwarded-For: ' . $_SERVER['REMOTE_ADDR'], 
      'Authorization: Basic ' . base64_encode($apiKey . ':' . $flags), 
     ), 
    ) 
); 

if ('POST' === $method || 'GET' === $method) { 
    $contextOptions['http']['header'][] = 'Content-Type: application/x-www-form-urlencoded'; 
} elseif ('PUT' === $method || 'UPDATE' === $method) { 
    $contextOptions['http']['header'][] = 'Content-Type: application/octet-stream'; 
} 

$contextOptions['http']['header'][] = 'Content-Length: ' . strlen($data); 
$contextOptions['http']['content'] = $data; 
$contextOptions['http']['header'] = implode("\r\n", $contextOptions['http']['header']); 
+0

둘 다 시도했지만 작동하지 않는 것 같습니다. 서버가 실행중인 PHP 버전을 볼 수 있듯이 5.2.17부터 5.2.10까지 'header'는 changelog에서 볼 수있는 것처럼 숫자로 인덱스 된 배열이 될 수 있습니다. http://php.net/manual/en /context.http.php –

+0

인덱스 배열은 절대로 효과가 없었습니다. 내가 프로젝트에서 사용하는 일부 코드로 내 대답을 편집했습니다. – BreyndotEchse

+0

코드 조각을 시도했지만 헤더가 여전히 제거되었습니다. 나는 'Authorization' 헤더를 볼 수 없습니다. 이 코드는 다른 서버에서 예상대로 작동하지만이 특정 서버가 헤더를 제거한다는 사실을 잊어 버렸습니다. –

0

인증 헤더가없는 주요 문제는 무엇입니까? .htaccess 파일을 다음과 같이 편집하여 비슷한 문제가 발생했습니다.


    RewriteEngine on 
    RewriteCond %{HTTP:Authorization} ^(.) RewriteRule . - [e=HTTP_AUTHORIZATION:%1] 

관련 문제