小编Spi*_*pir的帖子

使用Guzzle复制远程文件

我正在尝试将远程文件(图像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();
}
Run Code Online (Sandbox Code Playgroud)

当我这样做时,我的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'], …
Run Code Online (Sandbox Code Playgroud)

php guzzle

18
推荐指数
3
解决办法
3万
查看次数

试图克隆一个stdClass

我正在尝试克隆一个具有attribut的stdClass对象,这是一个DateTime.但它失败了.看起来克隆不起作用.我应该编写自己的__clone()方法吗?这有什么不对?

代码:

$object = new stdClass;
$object->date = new DateTime();
var_dump($object->date);

$cloned = clone($object);
$object->date->modify('+1 day');
var_dump($cloned->date);
Run Code Online (Sandbox Code Playgroud)

输出:

object DateTime (
    ->date = string (19) '2013-04-11 11:54:00'
    ->timezone_type = int 3
    ->timezone = string (13) 'Europe/Berlin'

object DateTime (
    ->date = string (19) '2013-04-12 11:54:00'
    ->timezone_type = int 3
    ->timezone = string (13) 'Europe/Berlin'
Run Code Online (Sandbox Code Playgroud)

php clone stdclass

6
推荐指数
2
解决办法
5118
查看次数

标签 统计

php ×2

clone ×1

guzzle ×1

stdclass ×1