避免重写已经存在的文件

xRo*_*bot 1 php

我编写了这个简单的代码来保存图像:

// $randomimage contains a random image url.
$content = file_get_contents($randomimage);
file_put_contents('images/'.$randomimage, $content);
Run Code Online (Sandbox Code Playgroud)

我需要一种不重写同名图像的方法。因此,如果我的 /images/ 文件夹中已存在具有特定名称的图像,则不执行任何操作。这很简单,但我不知道该怎么做。

nic*_*ckb 5

当然,使用file_exists.

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

值得注意的是,这本质上会在您的程序中引入竞争条件,因为另一个进程可能会在您检查文件是否存在的时间内创建该文件,然后写入该文件。在这种情况下,您将覆盖新创建的文件。然而,这种可能性极小,但却是有可能的。