Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
php-curl send HEAD request
<?php
// https://stackoverflow.com/questions/1545432/what-is-the-easiest-way-to-use-the-head-command-of-http-in-php
$dst_url='http://qq.com/';
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $dst_url);
// This changes the request method to HEAD
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,5); // connect timeout
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // curl timeout
// grab URL and pass it to the browser
if(FALSE === curl_exec($ch)){
echo('open '.$dst_url.' failed'."\n");
}else{
// Fetch the HTTP-code (cred: @GZipp)
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo('HTTP return code='.$retcode."\n");
}
// close cURL resource, and free up system resources
curl_close($ch);
@NewEXE

This comment has been minimized.

Copy link

@NewEXE NewEXE commented Aug 6, 2018

What about CURLOPT_CUSTOMREQUEST option?

$dst_url = 'http://qq.com/';
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $dst_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
curl_setopt($ch, CURLOPT_NOBODY, true);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close ($ch);

Otherwise you risk sending a GET request

@ErnestoBorio

This comment has been minimized.

Copy link

@ErnestoBorio ErnestoBorio commented Feb 8, 2019

The PHP documentation states that using CURLOPT_NOBODY changes the request mode to HEAD

http://php.net/manual/en/function.curl-setopt.php

CURLOPT_NOBODY: TRUE to exclude the body from the output. Request method is then set to HEAD
In the other hand, it does say:
CURLOPT_CUSTOMREQUEST: A custom request method to use instead of "GET" or "HEAD" when doing a HTTP request.

So CURLOPT_NOBODY should be fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment