我试图将远程文件(图像PNG,GIF,JPG ...)复制到我的服务器。我使用Guzzle,因为即使文件存在,我有时也会得到404和copy(),我还需要进行基本身份验证。此脚本位于由cron作业触发的长命令中。 我是非常新的Guzzle,我成功复制图像,但我的文件有错误的MIME类型。我一定在这里做错了什么。请建议我一个很好的方法来做到这一点(包括检查复制和MIME类型检查的成功/失败)。如果文件没有MIME类型,我会弹出一个包含详细信息的错误。使用Guzzle复制远程文件
下面是代码:
$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类型设置为应用程序/ x-空
而且看起来当状态是从200狂饮会自动不同的像抛出异常。我怎样才能停止这种行为,并自己检查状态,以便我可以自定义错误消息?
编辑:这对狂饮3.X 现在这是如何使用狂饮v 4.X(有狂饮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',
]);
或者使用狂饮流做到这一点:
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时有更好/合适的解决方案吗?
非常感谢!我会试试这个。我希望它保持propre MIME类型(原始MIME类型)。 – Spir
你需要做一些事情来更新磁盘上的文件以使用某种类型的MIME类型。我从来没有听说过这个。 –
不,我的意思是我打破它/打破了mime类型。你的解决方案工作正常谢谢您的帮助。 – Spir