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

如何在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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)