2013-06-29 43 views
0

我有web应用程序和api,我的登录系统与api一起工作,所以它重新变为:标题状态200,如果成功(用户名和密码正确),否则返回HTTP/1.0 401未经授权和json消息例如:{成功:0,“错误的用户名/密码”}php file_get_content returing 401 on

对于离(与邮差在谷歌浏览器插件测试)如果我想提出一个要求:

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

如果我的$的数据是正确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

你试图把一个'@''file_get_contents'之前抑制警告? – luk2302

+0

是的,它不显示'@'的错误,但它不返回响应json ex:'{success:0,“错误的用户名/密码”} –

+0

这是很期待的行为,因为HTTP 401指示一个错误,除了错误本身我不会返回任何东西。我假设你通过调用脚本中的header()创建错误? – luk2302

回答

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