[ACCEPTED]-What is the easiest way to use the HEAD command of HTTP in PHP?-head

Accepted answer
Score: 25

You can do this neatly with cURL:

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");

// This changes the request method to HEAD
curl_setopt($ch, CURLOPT_NOBODY, true);

// grab URL and pass it to the browser

// Edit: Fetch the HTTP-code (cred: @GZipp)
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE); 

// close cURL resource, and free up system resources


Score: 21

As an alternative to curl you can use the 4 http context options to set the request 3 method to HEAD. Then open a (http wrapper) stream 2 with these options and fetch the meta data.

$context  = stream_context_create(array('http' =>array('method'=>'HEAD')));
$fd = fopen('http://php.net', 'rb', false, $context);

see 1 also:

Score: 5

Even easier than curl - just use the PHPget_headers()function 7 which returns an array of all header info 6 for any URL you specify. And another real 5 easy way to check for remote file existence 4 is to usefopen()and try to open the URL in read 3 mode (you'll need to enable allow_url_fopen 2 for this).

Just check out the PHP manual 1 for these functions, it's all in there.

Score: 2
Score: 2

Use can use Guzzle Client, it use CURL library but more 2 simple and optimized.


composer require guzzlehttp/guzzle

example in your case:

// create guzzle object
$client = new \GuzzleHttp\Client();

// send request
$response = $client->head("https://example.com");

// extract headers from response
$headers = $response->getHeaders();

Fast 1 and easy.

Read more here

More Related questions