dpj83664 2013-06-06 02:51
浏览 382
已采纳

使用PHP从URL保存图像(以0KB文件大小保存)

What I'm trying to do:

file_get_contents() an online image, then save it to a directory on my server, with a new filename. The save path / directory is writable. CHMOD permissions: 777


What I've tried:

  • file_put_contents($filepath, file_get_contents($image_url)); // SAVES 0KB IMAGE

  • copy($image_url,$filepath); // SAVES 0KB IMAGE

  • cURL // SAVES 0KB IMAGE

So I'm already getting confused why none of this is working, when it should be...


Here are the relevant values inside my PHPinfo:

allow_url_fopen = On  
allow_url_include = On  
open_basedir = no value  

post_max_size = 8M  
upload_max_filesize = 50M  
upload_tmp_dir = no value  

max_execution_time = 18000  
max_file_uploads = 20  
max_input_nesting_level = 64  
max_input_time = 60  
max_input_vars = 1000  
memory_limit = 256M

And here is my full PHP code (I'm now using a function to save the image, because I'm just about desperate enough to try anything):

function save_image($inPath,$outPath)
{ // Download images from remote server
    $in=    fopen($inPath, "rb");
    $out=   fopen($outPath, "wb");
    while ($chunk = fread($in,8388608))
    {
        fwrite($out, $chunk, 8388608);
    }
    fclose($in);
    fclose($out);
}

// THE ORIGINAL IMAGE TO GET
$image_url = 'http://m1.i.pbase.com/u38/antidote3/upload/31848351.Cute.jpg';

// THE IMAGE EXTENSION
$image_type = substr(strrchr($image_url,"."),1);

// THE NEW FILE NAME
$filename   = 'product5_'. md5($image_url . $sku).'.'.$image_type;

// THE SAVE PATH
// OUTPUT: /var/www/site/media/catalog/product/FILE_NAME.FILE_TYPE
$filepath   = Mage::getBaseDir('media') . DS . 'catalog'. DS . 'product'. DS . $filename;

// SAVE THIS BIATCH!
save_image($image_url, $filepath);

// OTHER SAVE METHODS
// file_put_contents($filepath, file_get_contents($image_url));
// copy($image_url,$filepath);

Running strlen(file_get_contents($image_url)) on the image returns a big fat 0.
But shouldn't it work with the following enabled on my server?

allow_url_fopen = On  
allow_url_include = On

Apparently, the problem doesn't lie on the writing, but file_get_contents($image_url) doesn't have anything inside it.

Any ideas why? Thanks!


Other Information:

  • Platform: Magento
  • Language: PHP
  • PHP Version: 5.4.6
  • 写回答

3条回答 默认 最新

  • duanniu3385 2013-07-02 09:13
    关注

    The answer is: a firewall rule on the server was causing it. Thanks everyone for the help!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Delphi image图片缩放问题
  • ¥30 gradle环境下javafx项目如何使用druid连接池
  • ¥15 服务器打印水晶报表问题
  • ¥15 初学者用plt报错,求解答
  • ¥18 深度学习tensorflow1,ssdv1,coco数据集训练一个模型
  • ¥100 关于注册表摄像头和麦克风的问题
  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行