1

我有 web 应用程序和 api,我的登录系统与 api 一起使用,所以它会重新运行:如果成功(用户名和密码正确),则返回标头状态 200,否则返回 HTTP/1.0 401 Unauthorized 和 json 消息 ex: {success: 0 , "wrong用户名/密码"} (在谷歌浏览器中使用 POSTMEN 插件测试)

例如,如果我想提出请求:

$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 是正确的前用户名和密码,但如果不是,我没有收到错误消息,但是:

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 获取消息?

4

1 回答 1

0
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即可。

参考:http://php.net/manual/en/context.http.php

于 2017-03-13T20:27:12.423 回答