【问题标题】:save an image from a URL then save it into a directory php [duplicate]从 URL 保存图像,然后将其保存到目录 php [重复]
【发布时间】:2012-01-13 00:05:08
【问题描述】:

可能重复:
save image from php url using php

我如何使用 php 从另一个域(不在我的域/服务器上)保存/抓取图像并将其保存在我的站点目录中。

例如,图片的 URL 将是:

http://anothersite/images/goods.jpg

如何使用 PHP 抓取“good.jpg”,并将其保存在我的目录 www.mysite.com/directory/

我希望有人可以指导我。 谢谢!

【问题讨论】:

    标签: php


    【解决方案1】:

    您应该可以使用file_get_contents 来处理这个问题。为了使用带有file_get_contents 的URL,请确保在php.ini 文件中启用了allow_url_fopen

    define('DIRECTORY', '/home/user/uploads');
    
    $content = file_get_contents('http://anothersite/images/goods.jpg');
    file_put_contents(DIRECTORY . '/image.jpg', $content);
    

    确保您对要存储图像的目录具有写入权限;要使文件夹可写,您可以这样做:

    chmod +w /home/users/uploads
    

    参考文献

    1. file_get_contents
    2. allow_url_fopen
    3. chmod command

    【讨论】:

    • 感谢 Krister,但我怎样才能把它放在特定的目录中呢?
    【解决方案2】:

    这个链接可能会回答你的问题:

    http://stackoverflow.com/questions/909374/copy-image-from-remote-server-over-http
    

    对我来说,以下代码应该可以满足您的需求:

    $url = "http://other-site/image.png";
    $dir = "/my/local/dir/";
    $lfile = fopen($dir . basename($url), "w");
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)');
    curl_setopt($ch, CURLOPT_FILE, $lfile);
    
    fclose($lfile);
    curl_close($ch);
    

    【讨论】:

    • 您可以指定输出文件的相对或绝对路径,只要您对该特定目录具有写入权限。
    猜你喜欢
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2012-08-13
    • 2010-10-17
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多