我想将超文本传输协议的 HEAD 命令发送到 PHP 中的服务器以检索标头,但不检索内容或 URL。我如何有效地做到这一点?
最常见的用例可能是检查无效的网络链接。为此,我只需要 HTTP 请求的回复代码,而不需要页面内容。 使用
file_get_contents("http://...")
可以轻松地在 PHP 中获取网页,但是为了检查链接,这确实效率很低,因为它会下载整个页面内容/图像/其他内容。
您可以使用 cURL 巧妙地完成此操作:
<?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);
// For all details on the response(ex. content_length, etc)
// Uncomment:
# curl_setopt($ch, CURLOPT_HEADER, 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/response code:
echo $code;
// close cURL resource, and free up system resources
curl_close($ch);
作为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
甚至比curl更简单——只需使用PHP
get_headers()
函数即可返回您指定的任何URL的所有标头信息的数组。检查远程文件是否存在的另一种真正简单的方法是使用fopen()
并尝试以读取模式打开 URL(您需要为此启用allow_url_fopen)。
只需查看这些函数的 PHP 手册,都在那里。
我推荐使用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();
快速又简单。