相关疑难解决方法(0)

使用file_get_contents的HTTP请求,获取响应代码

我正在尝试file_get_contentsstream_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.有办法:

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

php http file stream

76
推荐指数
3
解决办法
7万
查看次数

标签 统计

file ×1

http ×1

php ×1

stream ×1