使用Guzzle检查远程文件是否存在的最佳方法是什么? [英] What is the best way to use Guzzle to check if a remote file exists?
本文介绍了使用Guzzle检查远程文件是否存在的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用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,因此我认为我可以使其更漂亮,更易读.
我是这样认为的吗?我该怎么办?
解决方案
我确实设法在文档中找到了部分答案. 枪口-请求方法 >
与 gist 结合使用,该功能可检查404状态.
/**
* @return boolean
*/
function exists()
{
$client = new GuzzleHttp\Client();
try {
$client->head($this->file);
return true;
} catch (GuzzleHttp\Exception\ClientException $e) {
return false;
}
}
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?
解决方案
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;
}
}
这篇关于使用Guzzle检查远程文件是否存在的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文