一尘不染

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

php

我试图file_get_contents一起使用stream_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。有没有办法:

  • 禁止显示警告(如果发生故障,我打算抛出自己的异常)
  • 从流中获取错误信息(至少是响应代码)

阅读 641

收藏
2020-05-29

共1个答案

一尘不染

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

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