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

时间:2009-10-09 18:42:32

标签: php http protocols head

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

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

5 个答案:

答案 0 :(得分:20)

您可以使用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);

答案 1 :(得分: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);

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

答案 2 :(得分:4)

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

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

答案 3 :(得分:2)

答案 4 :(得分:0)

使用可以使用Guzzle Client,它使用CURL库,但进行了优化

安装:

composer require guzzlehttp/guzzle

您的情况下的示例:

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

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

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

又快又简单。

Read more here