在PHP中使用HTTP的HEAD命令最简单的方法是什么?

fue*_*zig 13 php protocols http head

我想将超文本传输​​协议的HEAD命令发送到PHP中的服务器以检索标头,但不是内容或URL.我该如何以有效的方式做到这一点?

可能最常见的用例是检查死网链接.为此,我只需要HTTP请求的回复代码而不是页面内容.用PHP获取网页可以很容易地使用file_get_contents("http://..."),但是为了检查链接,这是非常低效的,因为它下载整个页面内容/图像/无论如何.

Pat*_*and 21

你可以用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);
Run Code Online (Sandbox Code Playgroud)


Vol*_*erK 18

作为curl的替代方法,您可以使用http上下文选项将请求方法设置为HEAD.然后使用这些选项打开(http包装器)流并获取元数据.

$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);
Run Code Online (Sandbox Code Playgroud)

另见:
http://docs.php.net/stream_get_meta_data
http://docs.php.net/context.http

  • stream_context_create()也可以与file_get_contents()一起使用。也许get_headers()与stream_context_set_default()更好地组合为&lt;code&gt; HEAD &lt;/ code&gt;的请求方法。参见http://php.net/manual/es/function.get-headers.php (2认同)

Bri*_*ian 5

甚至比 curl 更容易 - 只需使用 PHPget_headers()函数,该函数返回您指定的任何 URL 的所有标头信息的数组。检查远程文件是否存在的另一种真正简单的方法是使用fopen()并尝试以读取模式打开 URL(您需要为此启用 allow_url_fopen)。

只需查看这些函数的 PHP 手册,它就在那里。

  • `get_headers()` 实际上会发送一个 'GET' 请求,除非你先这样做: `stream_context_set_default(array('http'=&gt;array('method'=&gt;'HEAD')));` (6认同)