Php 使用cURL从URL保存图像

Php 使用cURL从URL保存图像,php,curl,Php,Curl,我需要将一个图像从url直接保存到我的服务器,我尝试了很多方法,但似乎都不能正常工作文件内容($file\u location,file\u get\u contents($image\u url))使我无法获取找到的文件目录错误。Simplefopen和fwrite不断返回损坏的图像。这一个工作,但它不断返回html文件,而不是jpg文件 function getimg($url) { $headers[] = 'Accept: image/gif, image/x-

我需要将一个图像从url直接保存到我的服务器,我尝试了很多方法,但似乎都不能正常工作<代码>文件内容($file\u location,file\u get\u contents($image\u url))使我无法获取找到的文件目录错误。Simple
fopen
fwrite
不断返回损坏的图像。这一个工作,但它不断返回html文件,而不是jpg文件

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent);         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://some/url/to/image.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image);
少了什么


谢谢。

您的代码工作正常。它从给定的url下载图像

您的问题将出现在存储图像的路径中

if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image);
在上面的代码中,检查路径./image/并给出与文件内容路径相同的路径。

此方法有效:

<?php

file_put_contents("/var/www/test/test.png", file_get_contents("http://www.google.com/intl/en_com/images/srpr/logo3w.png"));

?>


您需要启用
allow\u url\u fopen
,这是最简单的方法。请参见

您确定要下载的是图像文件而不是网页吗?你得到的HTML文件包含什么?对不起,我的错,我找到了解决方案,URL(图像名称)有“space”字符,所以我必须用“%20”替换它们。谢谢你的回复。