【问题标题】:What is the best way to use Guzzle to check if a remote file exists?使用 Guzzle 检查远程文件是否存在的最佳方法是什么?
【发布时间】:2018-11-07 21:20:24
【问题描述】:

我想使用 Guzzle 来检查远程文件是否存在。

这是我目前正在检查的示例:

/**
 * @return boolean
 */
function exists()
{
    // By default get_headers uses a GET request to fetch the headers.
    // Send a HEAD request instead
    stream_context_set_default(
        array(
            'http' => array(
                'method' => 'HEAD'
            )
        )
    );

    // Get the file headers
    $file_headers = @get_headers($this->file);

    // Check file headers for 404
    if($file_headers[0] == 'HTTP/1.1 404 Not Found')
        return false; // File not available.

    return true; // File is available!
}

但是,由于我已经在其他地方使用 Guzzle,我想我可以让这个更漂亮、更易读。

我这样想对吗?我将如何做到这一点?

【问题讨论】:

  • 你看过the docs吗?要发送 HEAD 请求,请使用 GuzzleHttp\Client::head 方法。从那里你只需要弄清楚如何检查 404。
  • @quickshiftin 谢谢,我确实设法在文档中找到了部分解决方案。
  • 干得好,我 +1 ;)

标签: php guzzle


【解决方案1】:

我确实设法在文档中找到了部分答案。 Guzzle - Request Methods

与具有类似功能的gist 结合使用,可检查 404 状态。

/**
 * @return boolean
 */
function exists()
{
    $client = new GuzzleHttp\Client();

    try {
        $client->head($this->file);
        return true;
    } catch (GuzzleHttp\Exception\ClientException $e) {
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 2010-09-18
    • 1970-01-01
    • 2010-09-21
    • 2011-05-25
    • 2012-08-29
    相关资源
    最近更新 更多