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

如何在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条)

报告相同问题?

悬赏问题

  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题