首页 > 解决方案 > curl 多次后不返回响应或 http 代码

问题描述

我想向网站发送许多请求并找到存在的最后一篇文章的 id。由于我的主机在多次请求后达到了对该网站的请求限制,我希望 curl 请求返回一个错误,以便我可以将最后一篇文章的 id 保存在我的数据库中并稍后继续滚动。但是在大约 200 个成功请求之后,curl 不返回任何响应或 http 代码。具体来说,我想从一个 id 到最后获取一个电报频道的帖子。这是我为此目的编写的函数:

function get_post_html_content($channel_username, $message_id){

  try {

    error_log($message_id."\n");

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, 
      "https://t.me/".$channel_username."/".$message_id."?embed=1");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);

    $headers = array();
    $headers[] = 'Pragma: no-cache';
    $headers[] = 'Sec-Fetch-Site: same-origin';
    $headers[] = 'Origin: https://t.me';
    $headers[] = 'Accept-Encoding: gzip,deflate';
    $headers[] = 'Accept-Language: en-US,en;q=0.9';
    $headers[] = 'Sec-Fetch-Mode: cors';
    $headers[] = 'Content-Type: application/x-www-form-urlencoded';
    $headers[] = 'Accept: */*';
    $headers[] = 'Cache-Control: no-cache';
    $headers[] = 'Referrer Policy: no-referrer-when-downgrade';
    $headers[] = 'Connection: keep-alive';
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $content = curl_exec($ch);

    if (!$content) {
      $errno = curl_errno($ch);
      $error = curl_error($ch);
      error_log("Curl returned error $errno: $error\n");
      curl_close($ch);
      return false;
     }
  $http_code = intval(curl_getinfo($ch, CURLINFO_HTTP_CODE));

  error_log("http code: ".$http_code."\n");

  } catch (Exception $e) {
    error_log($e->getMessage());
  }

  $content = gzdecode($content);

  curl_close($ch);

  return $content;
}

问题是在错误日志文件中打印了几次 http 代码 200 并且此函数返回内容后,突然它不会在错误日志中打印任何 http 代码,甚至不返回 false 所以我可以保存最后一个帖子 ID数据库。那么在这种情况下如何更改此函数以返回 false 呢?

标签: phpcurlweb-scrapinghttprequesttelegram

解决方案


推荐阅读