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

Php 将img从url复制到服务器:没有这样的文件或目录,php,fopen,fclose,Php,Fopen,Fclose,我正在使用php从url获取一个图像并将其复制到我的服务器,但出现了一个错误,说没有这样的文件 图像示例: http://www.google.co.in/intl/en_com/images/srpr/logo1w.png 以下是我正在使用的: //Get the file $content = file_get_contents("http://www.google.co.in/intl/en_com/images/srpr/logo1w.png"); //Store in the fil

我正在使用php从url获取一个图像并将其复制到我的服务器,但出现了一个错误,说没有这样的文件

图像示例:

http://www.google.co.in/intl/en_com/images/srpr/logo1w.png
以下是我正在使用的:

//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
文件夹(/location/to/save in here)应该存在。您还需要在其中具有写入权限


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');
✓ 这对我有用。
不使用
/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);

?>


确保您有权在所选位置创建文件您也可以使用文件内容而不是fopen/fwrite/fclose保存文件,而不是获取图像本身:)验证您的目标路径实际上这=>
rb+
需要=>
w
-我按原样尝试了您的代码,但它不起作用。只有当我将
rb+
更改为
w
时,我才创建了具有0755权限的文件夹。谢谢你的回答@Fred,我尝试了你的解决方案,现在它可以工作了。但是我仍然想知道为什么/location/to/save/notswork@JamesZhao不客气。这是因为
/location/to/save/
代表无效地址,除非您的服务器上有文件夹
location
和子文件夹
to
save
,但许多服务器配置为需要相对路径而不是绝对路径。如果您希望保存到其他文件夹,则需要使用影响
$fp=fopen(“../folder/image_google.jpg”,“w”)
@JamesZhao Plus,如果您觉得我已经回答了您的问题,并且问题已经解决,您可以单击左侧箭头下方的复选标记,并将其标记为“已回答”。否则,您的问题将保留在“未回答”类别中,干杯。@JamesZhao或
UPVOTE
。另外,请注意我对你接受的答案的评论:嗨,弗雷德,我是新来的。我只有7个名声,还不能推翻你的答案。非常感谢你的帮助。如果我还能做什么,请告诉我。