2

I have a URL that can be accessible via HTTP or HTTPS. I want to send a HEAD or GET request, which ever is fastest and get the response code so I know whether the URL is up or down.

How do I do that using Zend_HTTP_Client? I used get_headers() function, but it's very very slow on some remote servers. I am not sure if it handles HTTPS.

hakre
  • 193,403
  • 52
  • 435
  • 836
Jake
  • 25,479
  • 31
  • 107
  • 168
  • 1
    While `HEAD` could be faster, you may be better off using `GET` as not all servers will accept `HEAD` requests. `get_headers` will only be able to use `https` if PHP has `ssl` support on its native stream wrappers. Usually achieved by compiling PHP `--with-ssl`. – drew010 Mar 03 '12 at 20:54
  • @drew010 Good point about `HEAD`, just ran into that today - got a `405` if I tried `HEAD` (a case where I really only wanted to know if the file existed). – Tim Lytle Mar 03 '12 at 21:03

1 Answers1

5

You may not want to use Zend_Http_Client for this - use native PHP functions instead (like fsockopen since it seems you want this to be efficient).

That said, this may work for you (and since it defaults to the socket adapter, it may not be that less efficient than using the native functions):

$client = new Zend_Http_Client();
$response = $client->setUri($uri)->request(Zend_Http_Client::HEAD);

If not, you could try setting the cURL options manually.

$adapter = new Zend_Http_Client_Adapter_Curl();
$adapter->setCurlOption(CURLOPT_NOBODY, true);

$client = new Zend_Http_Client();
$client->setAdapter($adapter);
$response = $client->setUri($uri)->request(Zend_Http_Client::HEAD);

The code's not tested. Use at your own risk.

Tim Lytle
  • 17,549
  • 10
  • 60
  • 91
  • Nice answer, I agree a simple `fsockopen` may be sufficient for what he's doing, and will certainly require less overhead. – drew010 Mar 03 '12 at 20:54
  • @drew010 I may actually test them against each other, since by default `Zend_Http_Client` is using sockets. I guess you could save time by closing the connection as soon as you knew the URL was active (ignoring some of the headers). – Tim Lytle Mar 03 '12 at 21:02
  • the curl code works really nice..especially with the timeout value.. thanks – Jake Mar 04 '12 at 19:08