douniwan_0025 2013-09-18 03:21
浏览 38
已采纳

使用curl php将图像从网站保存到文件夹

I am able to save images from a website using curl like so:

//$fullpath = "/images/".basename($img);
$fullpath = basename($img);

$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawData = curl_exec($ch);
curl_close($ch);

if(file_exists($fullpath)) {
    unlink($fullpath);
}

$fp = fopen($fullpath, 'w+');
fwrite($fp, $rawData);
fclose($fp);

However, this will only save the image on the same folder in which I have the php file that executes the save function is in. I'd like to save the images to a specific folder. I've tried using $fullpath = "/images/".basename($img); (the commented out first line of my function) but this results to an error:

failed to open stream: No such file or directory

So my question is, how can I save the file on a specific folder in my project? Another question I have is, how can I change the filename of the image I save on the my folder? For example, I'd like to add the prefix siteimg_ to the image's filename. How do I implement this?

Update: I have managed to solve first problem with the path after trying to play around with the code a bit more. Instead of using $fullpath = "/images/".basename($img), I added a variable right before fopen and added it to the fopen method like so:

$path = "./images/";
$fp = fopen($path.$fullpath, 'w+');

Strangely that worked. So now I'm down to one problem which would be renaming the file. Any suggestions?

  • 写回答

1条回答 默认 最新

  • dongzhong8834 2013-09-18 03:32
    关注

    File paths in PHP are server paths. I doubt you have a /images folder on your server.

    Try constructing a relative path from the current PHP file, eg, assuming there is an images folder in the same directory as your PHP script...

    $path = __DIR__ . '/images/' . basename($img);
    

    Also, why don't you try this much simpler script

    $dest = __DIR__ . '/images/' . basename($img);
    copy($img, $dest);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?