Q:

PHP file_exists and save locally

I'm having a script that checks remote server for a file, and if it is already available locally it should use that one. If it isn't available locally, then download the image to the server. However, I'm struggling with the script overwriting images that I already have locally. If it's already available locally, the script shouldn't do anything with the file - just display it. 
In some cases, the script tries to download a image that I already have - and the filesize for the file it overwrites becomes 0kb even though the file worked perfectly earlier.
What am I doing wrong here?
<?php
 $url = "http://www.myserver.com/image123.jpg";
 $filename = basename($url);
 if(!file_exists(images/$filename))
 {
 // File doesn't exsist, download it!
    $image = file_get_contents("$url");
    file_put_contents("images/$filename", $image);
    $image = "images/$filename";
 } else {
 // We already got this file, display it!
    $image = "images/$filename";
 }
echo $image;
?>

A:

<?php

    $url = "http://www.myserver.com/image123.jpg";

    $filename = basename($url);

    $path = "images/$filename";

    if( !file_exists($path) ) {

        $image = file_get_contents($url);
        file_put_contents($path, $image);

    }

    echo $path;

?>

