1

I write this simple code to save an image:

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

I need a way to NOT rewrite an image with the same name. So, if an image with a certain name already exist in my /images/ folder, then do NOTHING. It's simple but I don't know how to do that.

xRobot
  • 25,579
  • 69
  • 184
  • 304
  • 3
    I have faith at some point you're going to start learning how to search for these things on your own instead of asking about [every](http://stackoverflow.com/questions/10389890/what-field-type-to-store-the-facebook-token) [single](http://stackoverflow.com/questions/10389560/what-is-the-best-field-to-store-the-birthday) [little](http://stackoverflow.com/questions/10311051/how-to-save-this-string-in-php) [question](http://stackoverflow.com/questions/10281742/how-to-know-if-a-certain-resource-exist). You can follow all your project's timelines by simply looking at your question history. – Mike B May 02 '12 at 13:23

3 Answers3

5

Sure, use file_exists.

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

It is important to note that this inherently introduces a race condition into your program, as it is possible that another process could create the file in the time it takes you to check for its existence, then write to the file. In this case, you would overwrite the newly created file. However, it is highly unlikely, but possible.

nickb
  • 59,313
  • 13
  • 108
  • 143
  • Well, it is not that unlikely. I had exactly the same piece of code in my "eshop", which created one file per order and it took about 14 days of ordering (avg 75 / day) for 4 occurenced of this to happen. Use flock to lock the file first. – Lukáš Řádek Jun 22 '21 at 20:25
2

In addition to nickb. is_file is better than file_exists, file_exists will return true on directories AND files.

So it would be:

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

PS: there is a function is_dir aswell, in case you were wondering.

LHolleman
  • 2,486
  • 2
  • 18
  • 19
  • Good point, although I'm not sure of `is_file`'s behaviour with symlinks, while `file_exists` properly handles them. – nickb Apr 24 '12 at 12:59
  • I used it multiple times and it will handle symlinks properly. – LHolleman Apr 24 '12 at 13:02
  • @LHolleman: If the file doesn't exist but the directory exists, then you have an unhandled error case and a E_WARNING. – netcoder Apr 24 '12 at 13:05
0

http://php.net/manual/en/function.file-exists.php

dm03514
  • 54,664
  • 18
  • 108
  • 145