geo*_*org 76 php http file stream
我正在尝试file_get_contents与stream_context_createPOST 一起使用.我的代码到目前为止:
$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);
Run Code Online (Sandbox Code Playgroud)
它工作正常,但是,当发生HTTP错误时,它会发出警告:
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
Run Code Online (Sandbox Code Playgroud)
并返回false.有办法:
小智 133
http://php.net/manual/en/reserved.variables.httpresponseheader.php
file_get_contents("http://example.com", false, ['ignore_errors' => true]);
var_dump($http_response_header);
Run Code Online (Sandbox Code Playgroud)
答案(包括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;
}
Run Code Online (Sandbox Code Playgroud)
这将导致无200响应,但是您可以从那里轻松地进行工作,例如,添加一个简单的Response类,return new Response((int) $status, $response);如果更适合您的用例。
例如,对POSTAPI端点执行JSON :
$response = fetch(
"POST",
"http://example.com/",
json_encode([
"foo" => "bar",
]),
[
"Content-Type: application/json",
"X-API-Key: 123456789",
]
);
Run Code Online (Sandbox Code Playgroud)
注意"ignore_errors" => true在http上下文映射中的使用-这将防止该函数针对非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);
Run Code Online (Sandbox Code Playgroud)
隐藏错误输出两个注释都可以,ignore_errors = true 或@(我更喜欢@)
| 归档时间: |
|
| 查看次数: |
74814 次 |
| 最近记录: |