使用cURL从URL保存图像

Heb*_*ian 5 php curl

我需要将图像从url直接保存到我的服务器,我尝试了很多方法,但似乎都没有正常工作.file_put_contents($file_location, file_get_contents($image_url));让我没有找到文件目录找到错误.简单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);
Run Code Online (Sandbox Code Playgroud)

缺了点什么?

谢谢.

nit*_*thi 3

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

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

if(file_exists('./image/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('image/'.$imagename,$image);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,检查路径 ./image/ 并给出 file_put_contents 路径中的路径。