dswe30290 2016-09-17 19:17
浏览 38

php函数的错误处理

How do I handle NULL returns on a function?

The below code is a basic curl function. I find there are times the $url will be NULL, for example if a website goes offline for some reason or a user types in a wrong url. In these instances I get an error "call to member function on null"

How do I return an empty result instead of a null result and stop the user from seeing this error?

function file_get_contents_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    $data = curl_exec($ch);

    curl_close($ch);

    return $data;
}
  • 写回答

1条回答 默认 最新

  • dsf1222 2016-09-17 19:27
    关注

    One potential avenue is Add:

    $headers = curl_getinfo($ch);
    

    then

    if($headers['http_code'] < 400){
       $data = "whatever you need it to be...";
    

    etc. and you can expand this for 300 (redirects) as necessary.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等