Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curl / Guzzle - get header / response code without body

To get the statuscode of a website with curl you can use the CURLOPT NOBODY.

Example:

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://www.example.com');
curl_setopt($curl , CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$status = curl_exec($curl);
curl_close($curl);

Is the following example with Guzzle as http library the same:

    $guzzle = new Client();
    $req = $guzzle->createRequest('GET', 'http://www.example.com');
    $result = $guzzle->send($req);

    $status = $result->getStatusCode();

My goal is to perform a curl/guzzle request without getting the body. Will that request with Guzzle only fetch the status code without wasting bandwith on other data?

like image 649
PeterDoesntKnow Avatar asked Feb 06 '15 00:02

PeterDoesntKnow


People also ask

How do I get responses from GuzzleHttp?

Both request and response messages can contain a body. You can check to see if a request or response has a body using the getBody() method: $response = GuzzleHttp\get('http://httpbin.org/get'); if ($response->getBody()) { echo $response->getBody(); // JSON string: { ... } }

What is GuzzleHttp in laravel?

A Guzzle is a PHP HTTP client that makes it easy to send HTTP requests with data, headers and trivial to integrate with web services. Guzzle is a simple interface for building query strings, POST requests, streaming large uploads, streaming large downloads, using HTTP cookies, uploading JSON data, etc.


1 Answers

In order to get status code of the response without downloading the whole content, you should use "head" method:

$client = new \GuzzleHttp\Client();
$response = $client->head('http://example.com/');
echo $response->getStatusCode();
like image 183
Igor Onachenko Avatar answered Oct 20 '22 16:10

Igor Onachenko