2016-11-01 3 views
0

cURL을 사용하여 일부 JSON 데이터를 POST하려고하지만 헤더를 설정하는 데 문제가 있습니다.PHP 5에서 cURL을 사용하여 JSON 데이터 게시

내 현재 코드는 그래서 다음과 같습니다 사용하여 로컬 호스트 (PHP 7)을 테스트 할 때

$ch = curl_init('https://secure.example.com'); 

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_HTTPHEADER, [ 
    'Content-Type: application/json', 
    'Content-Length: ' . strlen($data_string) 
]); 

if (!$result = curl_exec($ch)) 
{ 
    echo 'Failed: ' . curl_error($ch); 
    curl_close($ch); 
    die; 
} 

curl_close($ch); 

이 코드는 잘 작동합니다. 그러나 웹 서버는 PHP 5 만 실행하므로 CURLOPT_HTTPHEADER 옵션은 지원되지 않습니다.

내 코드에 그대로두면 "500 내부 오류"가 발생합니다. 제거 할 때 내 curl_exec()이 실행되지 않고 "실패 :"오류 메시지가 표시되지만 curl_error()이 표시되지 않습니다.

이 옵션이 없으면 cURL에서 JSON 데이터를 예상하도록 설정할 수 있습니까?

+0

웹 서버에 어떤 cURL 버전이 있습니까? – apokryfos

+0

500을 받으면 자세한 내용은 서버의 오류 로그를보십시오. –

+0

사실, * CURLOPT_HTTPHEADER 옵션은 PHP 5에서 지원되지 않습니다. *는 false입니다. – apokryfos

답변

1

curl_setopt($ch, CURLOPT_HTTPHEADER, [ 
'Content-Type: application/json', 
'Content-Length: ' . strlen($data_string) 
]); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', 
'Content-Length: ' . strlen($data_string) 
)); 

PHP가 [] 새로운 배열 구문을 지원 5.4+로 바꾸기 만, PHP가 < 5.4 요구 어레이()

short 배열 구 지원 가하고 PHP 5.4에서 http://php.net/manual/en/migration54.new-features.php

1

당신이 얻고있는 문제는 CURLOPT_HTTPHEADER에 관한 것이 아닙니다. 그것은 PHP를 오래되었습니다.

그러나 새 배열 구문 []PHP 5.4에 추가되었습니다.

은 당신의 코드를 변경

:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json', 
    'Content-Length: ' . strlen($data_string) 
)); 

하고 그것을 잘 작동합니다.

관련 문제