When you use the PHP copy function, the operation blindly copies over the destination file, even if it already exists. How do you copy a file safely, only performing the copy if there is no existing file?
When you use the PHP copy function, the operation blindly copies over the destination
Share
The obvious solution would be to call file_exists to check to see if the file exists, but doing that could cause a race condition. There is always the possibility that the other file will be created in between when you call file_exists and when you call copy. The only safe way to check if the file exists is to use fopen.
When you call fopen, set the mode to ‘x’. This tells fopen to create the file, but only if it doesn’t exist. If it exists, fopen will fail, and you’ll know that you couldn’t create the file. If it succeeds, you will have a created a file at the destination that you can safely copy over. Sample code is below: