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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?