如何保存图像,使其不会覆盖已创建的图像

I have the following code that saves an image but when it starts to save the next images it writes over the image that was already created. It does this 10 times and at the end I am left with one image and not 10 seperate images how can i fix this issue?

$album_id = $_GET['id'];
$url = 'http://website.com/xml/albums/site/'.$album_id.'/gallery/';
$xml = simplexml_load_file($url);

//album title and url
$album_title = $xml['title'];
$album_url = 'http://website.com'.$xml['html'];

//creates photo album directory
$thisdir = getcwd();
mkdir($thisdir."/".$album_id.' - '.$album_title , 0777);

//obtains all photos and saves them to a directory
foreach($xml as $xml_node) {
    $attributes = $xml_node->attributes();
    $file_url = 'http://website.com'.$attributes['src'];
    $file_name = $attributes['subtitle'];

    //save images
    copy($file_url, $thisdir.'/'.$album_id.' - '.$album_title.'/'.$file_name);

}

XML file

<photo src="/media/albums/1006969.jpg" title="Red" subtitle="01.jpg" />
<photo src="/media/albums/1006970.jpg" title="Red" subtitle="02.jpg" />
<photo src="/media/albums/100971.jpg" title="Red" subtitle="03.jpg" />
<photo src="/media/albums/1006972.jpg" title="Red" subtitle="04.jpg" />

Just check if the file exists, and if it does, change the name.

foreach($xml as $xml_node) {
    $attributes = $xml_node->attributes();
    $file_url = 'http://ebsite.com'.$attributes['src'];
    $file_name = $attributes['subtitle'];

    $path = $thisdir.'/'.$album_id.' - '.$album_title.'/'.$file_name;

    $i = 2;
    while(file_exists($path)) {
        $path = $thisdir.'/'.$album_id.' - '.$album_title.'/' . $i . '-' . $file_name;
        ++$i;
    }

    file_put_contents($path, file_get_contents($file_url));
}

That would make some pretty ugly named files, but hopefully you get the idea. Just come up with some kind of pattern (like prefixing it with an integer if it exists, starting with 2 and incrementing). Then, apply that pattern in a loop.

looks to me like you are depending on the $attributes['subtitle'] being unique. instead, maybe you need to use an actual unique index, such as the position of the XML node within its parent?

it seems the problem has nothing to do with saving files but most likely you are processing your XML wrong way.

first of all do a print_r($xml); and see what actual node you have to process to get the filenames.

it is also would be better to print filenames on the screen instead of creating actual files while you are sorting things out.