【问题标题】:What is the easiest way to use the HEAD command of HTTP in PHP?在 PHP 中使用 HTTP 的 HEAD 命令最简单的方法是什么?
【发布时间】:2010-12-05 10:48:31
【问题描述】:

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

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

【问题讨论】:

    标签: php http protocols head


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:
      【解决方案3】:

      作为 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 的解决方案,因为我喜欢使用内置函数。也许其他人可以评论每种可能性的表现?
      • 请注意,这将引发401 响应代码的错误,而 curl 为您提供实际响应。
      • stream_context_create() 也可以与file_get_contents() 一起使用。也许get_headers()stream_context_set_default() 结合到请求HEAD 的方法要好得多。见php.net/manual/es/function.get-headers.php
      【解决方案4】:

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

      只需查看这些函数的 PHP 手册,就可以了。

      【讨论】:

      • get_headers() 实际上会发送一个“GET”请求,除非你先这样做:stream_context_set_default(array('http'=&gt;array('method'=&gt;'HEAD')));
      【解决方案5】:

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

      【讨论】:

        猜你喜欢
        • 2015-11-15
        • 2010-09-23
        • 1970-01-01
        • 1970-01-01
        • 2015-09-04
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        相关资源
        最近更新 更多