php file_get_contents失败后返回401

时间:2013-06-29 10:41:16

标签: php api http-headers request httprequest

我有网络应用程序和api,我的登录系统与api一起工作,所以它重新执行:如果成功(用户名和密码正确)则标题状态200否则返回HTTP / 1.0 401 Unauthorized和json消息ex:{success:0 ,“用户名/密码错误”}(使用谷歌浏览器中的POSTMEN插件进行测试)

对于e.x,如果我想提出请求:

$method = "login";
$data = array("user"=>"test", "pass"=>"test");
send_re($method, $data);

这是我的函数send_re

function send_re($method, $data){
$url = "api.location/".$api_method;
    $options = array(
      'http' => array(
        'method'  => 'POST',
        'content' =>  http_build_query($data),
        'header'=>  "Content-Type: application/x-www-form-urlencoded\r\n" 

        )
    );

    $context  = stream_context_create( $options );
    $result = file_get_contents( $url, false, $context );

    return stripslashes( json_encode( $result) );
}

如果我的$ data是正确的e.x用户名和密码,但如果不是,我没有收到错误消息但是:

A PHP Error was encountered

Severity: Warning

Message: file_get_contents(http://85.10.229.108/home/login): failed to open stream: HTTP request       
 HTTP/1.0 401 Unauthorized

 Filename: libraries/api.php

有没有办法逃避这个问题并从api收到消息?

1 个答案:

答案 0 :(得分:0)

bind

只需添加function send_re($method, $data){ $url = "api.location/".$api_method; $options = array( 'http' => array( 'method' => 'POST', 'content' => http_build_query($data), 'header'=> "Content-Type: application/x-www-form-urlencoded\r\n", 'ignore_errors' => true ) ); $context = stream_context_create( $options ); $result = file_get_contents( $url, false, $context ); return stripslashes( json_encode( $result) ); } ,就可以了。

参考:'ignore_errors' => true