2012-04-24 79 views
1

我写这个简单的代码来保存图像文件:避免重写已经存在

// $randomimage contains a random image url. 
$content = file_get_contents($randomimage); 
file_put_contents('images/'.$randomimage, $content); 

我需要一种方法来没有使用相同的名字重写的图像。所以,如果具有某个名称的图像已经存在于我的/ images /文件夹中,那么请不要做任何事情。 这很简单,但我不知道该怎么做。

+3

我有信心在某些时候你会开始学习如何自己搜索这些东西,而不是询问[每个](http://stackoverflow.com/questions/10389890/what-field-type - 到 - 商店的Facebook标记)[单](http://stackoverflow.com/questions/10389560/what-is-the-best-field-to-store-the-birthday)[小](http :/ /问题](http://stackoverflow.com/questions/10281742/how-to-know-if-a - 某些资源并存)。您只需查看自己的问题历史记录,即可关注所有项目的时间表。 – 2012-05-02 13:23:13

回答

4

当然,请使用file_exists

$path = 'images/'.$randomimage; 
if(!file_exists($path)) { 
    // Note, see below 
    file_put_contents($path, $content); 
} 

需要注意的是这个固有地引入竞争条件到你的程序,因为这可能是因为另一个进程可以创建它需要你来检查它的存在,然后写信给当时的文件是非常重要的文件。在这种情况下,您会覆盖新创建的文件。然而,这是不太可能的,但可能的。

2

除了nickb。 is_file比file_exists更好,file_exists将在目录AND文件上返回true。

因此,这将是:

if(!is_file ('images/'.$randomimage)) { 
    file_put_contents('images/'.$randomimage, $content); 
} 

PS:有一个函数is_dir藏汉,如果你想知道。

+0

不错,虽然我不确定'is_file'是符号链接的行为,而'file_exists'正确地处理它们。 – nickb 2012-04-24 12:59:13

+0

我多次使用它,它会正确处理符号链接。 – LHolleman 2012-04-24 13:02:05

+0

@nickb:'is_file'解析符号链接。 – netcoder 2012-04-24 13:04:21