gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:07:39 27 4
gpt4 key购买 nike

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

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

最佳答案

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

关于php - 在 PHP 中使用 HTTP 的 HEAD 命令最简单的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1545432/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com