1

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?

4

1 回答 1

1

PHP 中的文件路径是服务器路径。我怀疑你/images的服务器上有一个文件夹。

尝试从当前 PHP 文件构造一个相对路径,例如,假设images在与您的 PHP 脚本相同的目录中有一个文件夹...

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

另外,你为什么不试试这个简单的脚本

$dest = __DIR__ . '/images/' . basename($img);
copy($img, $dest);
于 2013-09-18T03:32:01.753 回答