我编写了这个简单的代码来保存图像:
// $randomimage contains a random image url.
$content = file_get_contents($randomimage);
file_put_contents('images/'.$randomimage, $content);
我需要一种不重写同名图像的方法。因此,如果我的 /images/ 文件夹中已经存在具有特定名称的图像,则什么也不做。这很简单,但我不知道该怎么做。
我编写了这个简单的代码来保存图像:
// $randomimage contains a random image url.
$content = file_get_contents($randomimage);
file_put_contents('images/'.$randomimage, $content);
我需要一种不重写同名图像的方法。因此,如果我的 /images/ 文件夹中已经存在具有特定名称的图像,则什么也不做。这很简单,但我不知道该怎么做。
当然,使用file_exists
.
$path = 'images/'.$randomimage;
if( !file_exists( $path)) {
// Note, see below
file_put_contents( $path, $content);
}
重要的是要注意,这会在您的程序中固有地引入竞争条件,因为另一个进程可能会在您检查文件是否存在时创建文件,然后写入文件。在这种情况下,您将覆盖新创建的文件。然而,这是极不可能的,但有可能。
除了尼克b。is_file 比 file_exists 好,file_exists 将在目录和文件上返回 true。
所以它会是:
if( !is_file ( 'images/'.$randomimage)) {
file_put_contents('images/'.$randomimage, $content);
}
PS:还有一个函数 is_dir ,以防你想知道。