简体   繁体   English

PHP file_exists并保存在本地

[英]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. 在某些情况下,脚本会尝试下载我已经拥有的映像-即使文件运行更早,覆盖的文件的文件大小也变为0kb。

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

?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM