PHP catch无法打开流:HTTP请求失败!HTTP/1.1 401未经授权

Luk*_*ann 0 php error-handling oauth oauth-2.0

我正在尝试执行以下操作.

当我尝试使用oAuth访问服务时,如果我收到错误,因为我使用了错误的密钥,我想不显示错误消息,而是将用户发送到身份验证页面.

但是使用try catch fn不起作用.

这是我的代码:

$url = 'https://api.soundcloud.com/me.json?'.http_build_query(array(
        'oauth_token' => $token,
    ));
    //
    try{
        $user = json_decode(file_get_contents($url));
        return array(
            'uid' => $user->id,
            'nickname' => $user->username,
            'name' => $user->full_name,
            'location' => $user->country.' ,'.$user->country,
            'description' => $user->description,
            'image' => $user->avatar_url,
            'urls' => array(
                'MySpace' => $user->myspace_name,
                'Website' => $user->website,
            ),
        );
    }
    catch(Services_Soundcloud_Invalid_Http_Response_Code_Exception $e)
    {
        log_message('error', 'EXCEPTION: '.$e);
        return FALSE;
    }
Run Code Online (Sandbox Code Playgroud)

我希望这可以返回用户数组或FALSE.

有任何想法吗?

Ely*_*yx0 5

您可以在这里查看捕获file_get_content错误

如何在PHP中处理file_get_contents()函数的警告?

这提供了不同的解决方案,例如查看响应标头

$content = @file_get_contents("http://www.google.com");
if (strpos($http_response_header[0], "200")) { 
   echo "SUCCESS";
} else { 
   echo "FAILED";
}
Run Code Online (Sandbox Code Playgroud)