file_get_contents로 HTTP 요청, 응답 코드 받기
POST 요청을 file_get_contents
함께 사용 하려고 stream_context_create
합니다. 지금까지 내 코드 :
$options = array('http' => array(
'method' => 'POST',
'content' => $data,
'header' =>
"Content-Type: text/plain\r\n" .
"Content-Length: " . strlen($data) . "\r\n"
));
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
잘 작동하지만 HTTP 오류가 발생하면 경고를 내 보냅니다.
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
거짓을 반환합니다. 방법이 있습니까?
- (실패한 경우 자체 예외를 던질 계획입니다).
- 스트림에서 오류 정보 (적어도 응답 코드)를 가져옵니다.
http://php.net/manual/en/reserved.variables.httpresponseheader.php
file_get_contents("http://example.com");
var_dump($http_response_header);
OP에서 수락 한 답변을 포함하여 어떤 내용도 실제로 두 가지 요구 사항을 말씀하지 않습니다.
- (실패한 경우 자체 예외를 던질 계획입니다).
- 스트림에서 오류 정보 (적어도 응답 코드)를 가져옵니다.
내 의견은 다음과 달라집니다.
function fetch(string $method, string $url, string $body, array $headers = []) {
$context = stream_context_create([
"http" => [
// http://docs.php.net/manual/en/context.http.php
"method" => $method,
"header" => implode("\r\n", $headers),
"content" => $body,
"ignore_errors" => true,
],
]);
$response = file_get_contents($url, false, $context);
/**
* @var array $http_response_header materializes out of thin air
*/
$status_line = $http_response_header[0];
preg_match('{HTTP\/\S*\s(\d{3})}', $status_line, $match);
$status = $match[1];
if ($status !== "200") {
throw new RuntimeException("unexpected response status: {$status_line}\n" . $response);
}
return $response;
}
이것은 200
무응답 을 던질 것이지만,를 들어 간단한 예 Response
클래스를 추가하고 return new Response((int) $status, $response);
사용 사례에 더 적합하다면 거기에서 쉽게 작업 할 수 있습니다 .
예를 들어 POST
API 엔드 포인트에 JSON을 수행 한 다음 수행하십시오 .
$response = fetch(
"POST",
"http://example.com/",
json_encode([
"foo" => "bar",
]),
[
"Content-Type: application/json",
"X-API-Key: 123456789",
]
);
맵 컨텍스트 "ignore_errors" => true
에서를 사용 http
하면 함수가 non--2xx 상태 코드에 대해 오류를 발생시키지 않도록 방지 할 수 있습니다 .
이것은 대부분의 사용 사례에서 "적절한"가능성의 양일 가능성이 있습니다. @
연산자를 억제 오류 사용하지 않는 것이 좋습니다. 이는 동일한 오류 인수를 전달하는 것과 동일한 오류를 무시할 수 있습니다. 호출 코드.
http 코드를 포함하여 수락 된 응답에 몇 줄 더 추가
function getHttpCode($http_response_header)
{
if(is_array($http_response_header))
{
$parts=explode(' ',$http_response_header[0]);
if(count($parts)>1) //HTTP/1.0 <code> <text>
return intval($parts[1]); //Get code
}
return 0;
}
@file_get_contents("http://example.com");
$code=getHttpCode($http_response_header);
오류 출력을 숨기려면 두 주석 모두 괜찮습니다. ignore_errors = true 또는 @ (@ 선호합니다)
나는 다른 종류의 문제 로이 페이지로 이동하므로 내 답변을 게시합니다. 내 문제는 경고 알림을 억제하고 사용자에게 사용자 지정 경고 메시지를 표시하려고했기 때문에이 간단하고 분명한 수정이 도움이되었습니다.
// Suppress the warning messages
error_reporting(0);
$contents = file_get_contents($url);
if ($contents === false) {
print 'My warning message';
}
그리고 필요한 경우 그 후에 오류보고를 되돌립니다.
// Enable warning messages again
error_reporting(-1);
@file_get_contents
그리고 ignore_errors = true
동일하지 않습니다. 첫 번째는 아무것도 반환하지 않습니다. 두 번째는 오류 메시지를 억제하지만 서버 응답을 반환합니다 (예 : 400 잘못된 요청).
다음과 같은 기능을 사용합니다.
$result = file_get_contents(
$url_of_API,
false,
stream_context_create([
'http' => [
'content' => json_encode(['value1' => $value1, 'value2' => $value2]),
'header' => 'Authorization: Basic XXXXXXXXXXXXXXX',
'ignore_errors' => 1,
'method' => 'POST',
'timeout' => 10
]
])
);
return json_decode($result)->status;
200 (Ok) 또는 400 (Bad request)을 반환합니다.
완벽하게 작동하며 cURL보다 쉽습니다.
'ProgramingTip' 카테고리의 다른 글
JQuery 대 ExtJS (0) | 2020.10.14 |
---|---|
이미 ACCESS_FINE_LOCATION이있는 경우 ACCESS_COARSE_LOCATION을 생략 할 수 있습니까? (0) | 2020.10.14 |
프로그래밍 방식으로 뷰를 만들 때 자동 레이아웃 제약 조건을 어디에 설정해야합니까? (0) | 2020.10.14 |
csv import pandas 중 행 건너 뛰기 (0) | 2020.10.14 |
카르마 단위 테스트 중 이미지에 대한 404 경고를 수정하는 방법 (0) | 2020.10.14 |