gpt4 book ai didi

php - 带有 file_get_contents 的 HTTP 请求,获取响应代码

转载 作者:IT老高 更新时间:2023-10-28 11:55:19 24 4
gpt4 key购买 nike

我正在尝试将 file_get_contentsstream_context_create 一起使用来发出 POST 请求。到目前为止我的代码:

    $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

并返回 false。有没有办法:

  • 抑制警告(我打算在失败的情况下抛出自己的异常)
  • 从流中获取错误信息(至少是响应码)

最佳答案

http://php.net/manual/en/reserved.variables.httpresponseheader.php

$context = stream_context_create(['http' => ['ignore_errors' => true]]);
$result = file_get_contents("http://example.com", false, $context);
var_dump($http_response_header);

关于php - 带有 file_get_contents 的 HTTP 请求,获取响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15620124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com