【问题标题】:php file_get_content returing 401 on failedphp file_get_content 在失败时返回 401
【发布时间】:2013-06-27 02:10:42
【问题描述】:

我有 web 应用程序和 api,我的登录系统与 api 一起使用,因此它会返回:如果成功(用户名和密码正确),则返回标头状态 200,否则返回 HTTP/1.0 401 Unauthorized 和 json 消息 ex: {success: 0 , “错误的用户名/密码”}(使用谷歌浏览器中的 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 是正确的 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获取消息?

【问题讨论】:

  • 您是否尝试过在file_get_contents 之前添加@ 来禁止警告?
  • 是的,它不会显示 @ 的错误,但它不会返回响应 json e.x: {success: 0 , "wrong username/password"}
  • 这几乎是预期的行为,因为 HTTP 401 指示错误并且我猜除了错误本身之外不返回任何内容。我假设您在调用的脚本中通过 header() 创建了错误?
  • 使用@ 确实应该抑制警告,但它也会抑制更严重错误的报告。不是最佳做法。
  • @luk2302 是的,头 401 是在被调用的脚本中创建的。

标签: php api http-headers request httprequest


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2012-07-27
    • 2017-01-26
    • 1970-01-01
    • 2011-09-22
    相关资源
    最近更新 更多