What is the best way to use Guzzle to check if a remote file exists?

橙三吉。 提交于 2020-01-12 08:07:48

问题


I would like to use Guzzle to check if a remote file exists.

This is an example of how I am currently checking:

/**
 * @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!
}

However, since I'm already using Guzzle elsewhere, I'd think I could make this prettier and more readable.

Am I right in thinking that? How would I accomplish that?


回答1:


I did manage to find part of the answer in the docs. Guzzle - Request Methods

Combined with a gist that has a similar function, that checks for 404 status.

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

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


来源:https://stackoverflow.com/questions/26555661/what-is-the-best-way-to-use-guzzle-to-check-if-a-remote-file-exists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!