title: PHP curl "Couldn't resolve host"
body: <p>I'm connecting to a public API in order to sync some content between two sites. PHP CURL is used for accessing the JSON API and for downloading binary images (the code example below does not cover binary download for simplicity reasons!). </p>
  
  <p>Everything works fine, until after several hundred requests, I get "Couldn't resolve host" from curl_error($ch), the response $body is empty and the returned $http_code is 0. The curl returns empty responses until the script is done working. The url's are definitely correct.</p>
  
  <p><strong>System</strong></p>
  
  <p>The script is running on a Debian Linux 6.0 machine with PHP 5.3.3-7+squeeze26.</p>
  
  <p><strong>Already tried:</strong></p>
  
  <ol>
  <li>Turned on PHP CURLOPT_VERBOSE in order to see if I could get anything useful what there could be happening, but no luck.</li>
  <li>Tried to sleep(10) - 15 secs after such an error event happens and restart the request, but the request fails as before.</li>
  <li>Measured the memory consumption with memory_get_usage(). The script has 2GB memory limit and the error happens when the memory consumption is at about 150M, so I don't think this could be the problem</li>
  </ol>
  
  <p>Any ideas what could be causing this behaviour?</p>
  
  <p><strong>Curl Code</strong></p>
  
  <pre><code>function getData($url, $countRetries = 0) {
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);            
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_HEADER, true);
      curl_setopt($ch, CURLOPT_VERBOSE, 1);
      curl_setopt($ch, CURLOPT_STDERR, $log_stderr = fopen('/var/log/curl.log', 'a'));
      curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));    
  
      $response = curl_exec($ch);
  
      $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
      $header = substr($response, 0, $header_size);  
      $body = substr($response, $header_size);
  
      $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      $error = curl_error($ch);
  
      curl_close($ch);
      fclose($log_stderr);
  
      if ($http_code == 0 &amp;&amp; $countRetries &lt; 3) {
          sleep(10); 
          return getData($data, $countRetries);
      }
  
      return $body;
  }
  </code></pre>