PHP file_exists 并保存在本地

PHP file_exists and save locally

我有一个脚本可以检查远程服务器上的文件,如果它已经在本地可用,它应该使用那个。如果本地不可用,则将图像下载到服务器。但是,我正在为脚本覆盖本地已有的图像而苦苦挣扎。如果它已经在本地可用,则脚本不应对该文件执行任何操作 - 只需显示它即可。

在某些情况下,该脚本会尝试下载我已经拥有的图像 - 并且它覆盖的文件的文件大小变为 0kb,即使该文件之前运行良好。

我做错了什么?

<?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;
?>
<?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;

?>