【问题标题】:PHP file_exists and save locallyPHP file_exists 并保存在本地
【发布时间】:2015-12-05 00:05:23
【问题描述】:

我有一个检查远程服务器的文件的脚本,如果它已经在本地可用,它应该使用那个。如果本地不可用,则将图像下载到服务器。但是,我正在努力用脚本覆盖我在本地已经拥有的图像。如果它已经在本地可用,脚本不应该对文件做任何事情 - 只是显示它。

在某些情况下,脚本会尝试下载我已经拥有的图像 - 并且它覆盖的文件的文件大小变为 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;
?>

【问题讨论】:

  • 我觉得应该是这样的 file_exists('images/'.$filename))
  • 我会试试看 :)

标签: php image file download file-exists


【解决方案1】:
<?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;

?>

【讨论】:

  • 效果很好!愿意解释一下我的脚本做错了什么吗? :)
  • 你只是缺少了一些引用:if(!file_exists(images/$filename)) 每当你在多个地方有相同的表达式时,最好存储在一个变量中并使用该变量,减少错误。
  • 感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 2016-04-29
  • 2013-09-06
  • 2011-10-02
  • 1970-01-01
  • 2016-01-23
相关资源
最近更新 更多