将img从url复制到服务器:没有这样的文件或目录

时间:2013-08-14 22:35:08

标签: php fopen fclose

我使用php从url获取图像并将其复制到我的服务器但是收到错误说没有这样的文件

图片示例:

http://www.google.co.in/intl/en_com/images/srpr/logo1w.png

以下是我正在使用的solution

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("/location/to/save/image.jpg", "w");
fwrite($fp, $content);
fclose($fp);

我收到以下错误。我做错了什么?

fopen(/location/to/save/image.jpg): failed to open stream: No such file or directory

3 个答案:

答案 0 :(得分:1)


  

✓这对我有用。


在没有/location/to/save/

的情况下尝试

该文件将保存在您运行脚本的同一文件夹中。

如:

<?php

//Get the file
$content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png");
//Store in the filesystem.
$fp = fopen("image_google.jpg", "w");
fwrite($fp, $content);
fclose($fp);

?>

答案 1 :(得分:0)

该文件夹(/ location / to / save in)应该存在。您还需要其中的写权限。

答案 2 :(得分:0)

function download_image($url,$destination_path = '')
{  
    // CHECKS IF CURL DOES EXISTS. SOMETIMES WEB HOSTING DISABLES FILE GET CONTENTS
    if (function_exists('curl_version'))
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $content = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

    } else
    {
        $content = file_get_contents($url);
    }
    // CHECKS IF DIRECTORY DOESNT EXISTS AND DESTINATION PATH IS NOT EMPTY
    if(!file_exists($destination_path) && $destination_path != ''){
        mkdir($destination_path, 0755, true);  
    }
    // ATTEMPT TO CREATE THE FILE
    $fp = fopen($destination_path.'/'.date('YmdHis').".jpg", "a+");
    fwrite($fp, $content);
    fclose($fp); 
}

download_image('http://davidwalsh.name/wp-content/themes/jack/images/treehouse-1.png','images');