diff --git a/src/Httpful/Request.php b/src/Httpful/Request.php index b9b03e6..a722d39 100644 --- a/src/Httpful/Request.php +++ b/src/Httpful/Request.php @@ -126,6 +126,14 @@ public function hasTimeout() return isset($this->timeout); } + /** + * @return bool does the request have a connection timeout? + */ + public function hasConnectionTimeout() + { + return isset($this->connection_timeout); + } + /** * @return bool has the internal curl request been initialized? */ @@ -167,6 +175,23 @@ public function timeoutIn($seconds) return $this->timeout($seconds); } + /** + * Specify a HTTP connection timeout + * @param float|int $timeout seconds to timeout the HTTP connection + * @return Request + * @throws Exception + */ + public function setConnectionTimeout($connection_timeout) + { + if (!preg_match('/^\d+(\.\d+)?/', $connection_timeout)) { + throw new \InvalidArgumentException( + "Invalid connection timeout provided: " . var_export($connection_timeout, true) + ); + } + $this->connection_timeout = $connection_timeout; + return $this; + } + /** * If the response is a 301 or 302 redirect, automatically * send off another request to that location @@ -875,6 +900,14 @@ public function _curlPrep() } } + if ($this->hasConnectionTimeout()) { + if (defined('CURLOPT_CONNECTTIMEOUT_MS')) { + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connection_timeout * 1000); + } else { + curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $this->connection_timeout); + } + } + if ($this->follow_redirects) { curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, $this->max_redirects);