我想在PHP中向服务器发送Hypertext Transfer Protocol的HEAD命令,以检索头部而非内容或URL。如何以高效的方式实现此功能?
最常见的用途可能是检查无法访问的网页链接。为此,我仅需要HTTP请求的响应代码,而不需要页面内容。在PHP中获取网页可以使用file_get_contents("http://...")
轻松完成,但为了检查链接,这样做效率非常低下,因为它会下载整个页面内容/图像/等等。
<?php
// create a new cURL resource with the url
$ch = curl_init( "http://www.example.com/" );
// This changes the request method to HEAD
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute curl with the configured options
curl_exec($ch);
// Edit: Fetch the HTTP-code (cred: @GZipp)
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// To print the response code:
print( $code);
// To check the size/length:
$length = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
// To print the content_length:
print( "<br>\n $length bytes");
// close cURL resource, and free up system resources
curl_close($ch);
除了使用 curl,您还可以使用 http 上下文选项将请求方法设置为 HEAD
。然后,使用这些选项打开一个 (http wrapper) 流并获取元数据。
$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
get_headers()
函数即可返回指定URL的所有标头信息数组。另一个检查远程文件存在性的简单方法是使用fopen()
并尝试以读取模式打开URL(您需要启用allow_url_fopen)。只需查看PHP手册即可了解这些函数的详细信息。stream_context_set_default(array('http'=>array('method'=>'HEAD')))
, get_headers()
实际上会发送一个 'GET' 请求。 - Octopus我建议使用 Guzzle 客户端,它基于 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();
快速且简便。
点击此处 了解更多信息。
xmlhttp.open("HEAD", url);
xmlhttp.send();
xmlhttp.status // (200 meaning 'OK, success', 404 'not found', etc)
xmlhttp.getResponseHeader('Content-Length');
// and for all:
xmlhttp.getAllResponseHeaders();
401
响应代码,这将抛出错误,而 curl 则提供实际响应。 - Fabian Schmenglerstream_context_create()
也可以与file_get_contents()
一起使用。也许get_headers()
结合stream_context_set_default()
更适用于请求方法为<code>HEAD</code>的情况。请参阅http://php.net/manual/es/function.get-headers.php。 - cybmeta