如何使用php从url保存图像,如果已经存在则替换

i am trying to save a video thumbnail from dailymotion i can bring the image URL but the actual problem i am getting is to save that thumbnail on my server by renaming image. Secondly i want to check that name if the name is already exist on the server it can replace the older one this function is basically used on updating video id.

Here is my php code to grab dailymotion video thumbnail url but i don't know to to save it

<?php
$related_dm_code = "x2rxn6i"; //Video Code
$thumbd_item='https://api.dailymotion.com/video/'.$related_dm_code.'?fields=thumbnail_240_url';
$json_thumbnail2_item = file_get_contents($thumbd_item);
$get_thumbnail2_item = json_decode($json_thumbnail2_item, TRUE);
$thumb2_item=$get_thumbnail2_item['thumbnail_240_url'];
echo $thumb2_item; //display thumbnail url
?>

e.g. here is the thumbnail url:

anothersite.com/images/demo-image.jpg

How can i save image in this path of my URL:

mysite.com/video_thumbs/

and renaming demo-image.jpg to anyothername.jpg

and then a last part of the function to check and replace if anyothername.jpg is already exist then replace with the older one this would be used to updating mysql

You mean something like:

if (!file_exists('http://www.example.com/video_thumbs/' . $file)) {
   $img = file_get_contents("http://www.anothersite.com/images/demo-image.jpg");

   file_put_contents('http://www.example.com/video_thumbs/' . $file, $img);
}