What is the easiest way to use the HEAD command of

2019-01-18 05:21发布

I would like to send the HEAD command of the Hypertext Transfer Protocol to a server in PHP to retrieve the header, but not the content or a URL. How do I do this in an efficient way?

The probably most common use-case is to check for dead web links. For this I only need the reply code of the HTTP request and not the page content. Getting web pages in PHP can be done easily using file_get_contents("http://..."), but for the purpose of checking links, this is really inefficient as it downloads the whole page content / image / whatever.

4条回答
ゆ 、 Hurt°
2楼-- · 2019-01-18 05:21

As an alternative to curl you can use the http context options to set the request method to HEAD. Then open a (http wrapper) stream 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);
var_dump(stream_get_meta_data($fd));
fclose($fd);

see also:
http://docs.php.net/stream_get_meta_data
http://docs.php.net/context.http

查看更多
贼婆χ
3楼-- · 2019-01-18 05:23

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

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

查看更多
Ridiculous、
4楼-- · 2019-01-18 05:47
smile是对你的礼貌
5楼-- · 2019-01-18 05:48

You can do this neatly with cURL:

<?php
// 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
curl_exec($ch);

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

// close cURL resource, and free up system resources
curl_close($ch);
查看更多
登录 后发表回答