douzhuoxia0587 2017-01-23 08:40
浏览 104
已采纳

如何在file_get_contents()中处理403错误?

I'm getting 403 errors when using file_get_contents(),

I want to handle this error like this,

if(required_function(file_get_contents($url))){  //detects there is a 403
    error
// do some special set of tasks
}else{
    //run normally
}

I tried to read the error since the url shows the error when I pasted in the browser , but is not getting in to file_get_contents() so I failed. I don't think changing user agent will work because systems may still be able to detect this is a script ,so I realized if I could detect the 403 error, the script will not crash.

any ideas ?

please help , I'm new to programming. thanks a lot.

  • 写回答

2条回答 默认 最新

  • douyun1972 2017-01-23 08:55
    关注

    Personally I'm suggesting you to use cURL instead of file_get_contents. file_get_contents is great for basic content oriented GET requests. But the header, HTTP request method, timeout, redirects, and other important things do not matter for it.

    Nevertheless, to detect status code (403, 200, 500 etc.) you can use get_headers() call or $http_response_header auto-assigned variable.

    $http_response_header is a predefined variable and it is updated on each file_get_contents call.

    Following code may give you status code (403, 200 etc) directly.

    preg_match( "#HTTP/[0-9\.]+\s+([0-9]+)#", $http_response_header[0], $match);
    $statusCode = intval($match[1]);
    

    For more information and content of variable please check official documentation

    $http_response_header — HTTP response headers

    get_headers — Fetches all the headers sent by the server in response to a HTTP request

    (Better Alternative) cURL

    Warning about $http_response_header, (from php.net)

    Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines. Any HTTP header received that is longer than this will be ignored and won't appear in $http_response_header. The cURL extension doesn't have this limit.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?