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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀