【发布时间】:2013-06-01 03:29:17
【问题描述】:
我正在尝试将远程文件(图像 PNG、GIF、JPG ...)复制到我的服务器。我使用Guzzle,因为即使文件存在,我有时也会用copy() 得到404,而且我还需要进行基本身份验证。该脚本位于由 cron 作业触发的命令中启动的长脚本中。 我对 Guzzle 很陌生,我成功复制了图像,但我的文件的 mime 类型错误。我一定在这里做错了什么。请建议我这样做的好方法(包括检查复制成功/失败和 mime 类型检查)。如果文件没有 mime 类型,我会弹出带有详细信息的错误。
代码如下:
$remoteFilePath = 'http://example.com/path/to/file.jpg';
$localFilePath = '/home/www/path/to/file.jpg';
try {
$client = new Guzzle\Http\Client();
$response = $client->send($client->get($remoteFilePath)->setAuth('login', 'password'));
if ($response->getBody()->isReadable()) {
if ($response->getStatusCode()==200) {
// is this the proper way to retrieve mime type?
//$mime = array_shift(array_values($response->getHeaders()->get('Content-Type')));
file_put_contents ($localFilePath , $response->getBody()->getStream());
return true;
}
}
} catch (Exception $e) {
return $e->getMessage();
}
当我这样做时,我的 mime 类型设置为 application/x-empty
另外,当状态与 200 不同时,Guzzle 会自动抛出异常。如何停止这种行为并自己检查状态,以便自定义错误消息?
编辑:这是用于 Guzzle 3.X 现在,您可以使用 Guzzle v 4.X 来做到这一点(与 Guzzle 6 也一样)
$client = new \GuzzleHttp\Client();
$client->get(
'http://path.to/remote.file',
[
'headers' => ['key'=>'value'],
'query' => ['param'=>'value'],
'auth' => ['username', 'password'],
'save_to' => '/path/to/local.file',
]);
或使用 Guzzle 流:
use GuzzleHttp\Stream;
$original = Stream\create(fopen('https://path.to/remote.file', 'r'));
$local = Stream\create(fopen('/path/to/local.file', 'w'));
$local->write($original->getContents());
这看起来很棒。使用 Guzzle 4 时是否有更好/合适的解决方案?
【问题讨论】: