带有 file_get_contents 的 HTTP 请求,获取响应代码 [英] HTTP requests with file_get_contents, getting the response code

查看:46
本文介绍了带有 file_get_contents 的 HTTP 请求,获取响应代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use file_get_contents together with stream_context_create to make POST requests. My code so far:

    $options = array('http' => array(
        'method'  => 'POST',
        'content' => $data,
        'header'  => 
            "Content-Type: text/plain
" .
            "Content-Length: " . strlen($data) . "
"
    ));
    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

它工作正常,但是,当发生 HTTP 错误时,它会发出警告:

It works fine, however, when an HTTP error occurs, it spits out a warning:

file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

并返回 false.有没有办法:

and returns false. Is there a way to:

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

推荐答案

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);

这篇关于带有 file_get_contents 的 HTTP 请求,获取响应代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆