【问题标题】:Copy image from URL using PHP使用 PHP 从 URL 复制图像
【发布时间】:2014-09-18 02:50:28
【问题描述】:

我想使用 PHP 将图像从 url 复制到我的服务器。
我看到了这个答案Saving image from PHP URL
并尝试过:

<?php

$url = 'https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p200x200/548412_147785902099377_260065314_n.jpg?oh=5c97dcd58931398e501666daee4c4ae8&oe=5457AC73&__gda__=1414911437_494ad1af138ee7670f89f4a6ba8b6d06';
$img = 'flower.jpg';
copy($url, $img);

?>

但我收到以下错误:

failed to open stream: No connection could be made because the target machine actively refused it.

我的 php 版本是 5.4,在我的 php.ini allow_url_fopen=On
我找不到如何解决这个问题,有什么聪明的建议吗?

【问题讨论】:

  • 也许你可以使用file_get_contents 与您链接到的问题的已接受答案一样。
  • 该服务器不喜欢您尝试以这种方式访问​​其文件。 See this previous question - 同时,把https 中的s 去掉,看看是否有帮助。
  • @CompuChip - 这与底层机制完全相同。
  • @Deryck 同样的错误仍然存​​在。

标签: php image url


【解决方案1】:

我可以在命令行中用简单的curl 抓取它:

curl "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p200x200/548412_147785902099377_260065314_n.jpg?oh=5c97dcd58931398e501666daee4c4ae8&oe=5457AC73&__gda__=1414911437_494ad1af138ee7670f89f4a6ba8b6d06" > bill.jpg

也许你可以使用 php 的 system 来做到这一点?

【讨论】:

    【解决方案2】:

    使用 file_put_contents 而不是 copy.use 下面的代码

    file_put_contents($img, file_get_contents($url));
    

    【讨论】:

    • 同样的错误仍然存​​在。
    【解决方案3】:

    使用 curl 怎么样,然后你可以直接写入文件。

    <?php
    $url = 'https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xap1/v/t1.0-1/p200x200/548412_147785902099377_260065314_n.jpg?oh=5c97dcd58931398e501666daee4c4ae8&oe=5457AC73&__gda__=1414911437_494ad1af138ee7670f89f4a6ba8b6d06';
    
    $fp = fopen ('./flower.jpg', 'w+');
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERAGENT, 'YourBot.0.1');
    curl_setopt($ch, CURLOPT_FILE, $fp); // write curl response to file
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  false); //required!
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  false); //required!
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    ?>
    

    【讨论】:

    • 奇怪...这里没有问题,我测试过它并且它有效。如果 fb 实际上阻止了您尝试它的主机,我会受伤,如果您在本地测试它,请检查您至少可以在浏览器中查看图像。
    • 还要检查你是否安装了 curl
    猜你喜欢
    • 2012-04-05
    • 2012-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 2017-09-21
    • 1970-01-01
    • 2011-09-22
    • 2013-05-11
    相关资源
    最近更新 更多