【问题标题】:Why curl not work when use with if condition? [closed]为什么在 if 条件下使用 curl 不起作用? [关闭]
【发布时间】:2015-10-28 17:49:17
【问题描述】:

我尝试在 if 条件下使用 curl,它不起作用。

if($_GET[test] != '')
{
    $fb = new FacebookDebugger();
    $fb->reload('http://www.example.com');

    class FacebookDebugger
    {
        public function reload($url)
        {
            $graph = 'https://graph.facebook.com/';
            $post = 'id='.urlencode($url).'&scrape=true';
            return $this->send_post($graph, $post);
        }
        private function send_post($url, $post)
        {
            $r = curl_init();
            curl_setopt($r, CURLOPT_URL, $url);
            curl_setopt($r, CURLOPT_POST, 1);
            curl_setopt($r, CURLOPT_POSTFIELDS, $post);
            curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($r, CURLOPT_CONNECTTIMEOUT, 5);
            $data = curl_exec($r);
            curl_close($r);
            return $data;
        }
    }
}

但是当删除 if 条件时,curl 会很好用。

如何在 if 条件下使用 curl?

【问题讨论】:

  • 不要把类放在 if 语句中
  • $_GET[test] 很可能应该被引用 $_GET['test'] - 这会引发未定义的常量测试通知。
  • 将错误报告添加到文件顶部,紧跟在您的打开 PHP 标记之后,例如 <?php error_reporting(E_ALL); ini_set('display_errors', 1);,然后是其余代码,以查看它是否产生任何结果。如果是这样,请告诉我们这表明了什么。如果它显示为未定义的常量通知,那么您将知道该怎么做。

标签: php facebook curl


【解决方案1】:

您正在尝试在初始化之前调用函数,请尝试以下代码。

class FacebookDebugger
{
    public function reload($url)
    {
        $graph = 'https://graph.facebook.com/';
        $post = 'id='.urlencode($url).'&scrape=true';
        return $this->send_post($graph, $post);
    }

    private function send_post($url, $post)
    {
        $r = curl_init();
        curl_setopt($r, CURLOPT_URL, $url);
        curl_setopt($r, CURLOPT_POST, 1);
        curl_setopt($r, CURLOPT_POSTFIELDS, $post);
        curl_setopt($r, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($r, CURLOPT_CONNECTTIMEOUT, 5);
        $data = curl_exec($r);
        curl_close($r);
        return $data;
    }
}

if (isset($_GET[test]) && $_GET[test] != '') {
    $fb = new FacebookDebugger();
    $fb->reload('http://www.example.com');
}

【讨论】:

  • OP:“但是当删除 if 条件时,curl 会很好用。” 也可能与 $_GET[test] 未被引用有关。
  • 旁注:if (isset($_GET[test]) && $_GET[test] != '') 可以简化为 if(!empty($_GET[test]))
  • @Fred-ii- 始终使用 isset 检查某个变量的存在。当没有定义“测试”变量时,尝试访问 $_GET[test] 也会引发 E_Notice。用 isset 检查可以避免这种情况。
  • 我引用stackoverflow.com/a/7191642 :"Empty 检查变量是否已设置,如果是,则检查它是否为 null、""、0 等"。
  • 并从手册php.net/manual/en/function.empty.php 我引用: “如果变量不存在,则不会生成警告。这意味着 empty() 本质上等同于 !isset($var) || $var == false。” - 但是,在某些特殊情况下,您可能是对的。
猜你喜欢
  • 2020-11-16
  • 2016-07-24
  • 2022-01-21
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
相关资源
最近更新 更多