Skip to content
PHP Logo

How does PHP handle file overwriting in a directory?

When writing files to a directory in PHP, it's important to handle the case where a file with the same name already exists. If not properly handled, the new file may overwrite the existing one, potentially causing data loss. To prevent this, you can check if the file already exists before writing to it, and either rename the new file or prompt the user for action.

php
$filename = 'example.txt';
$directory = 'path/to/directory/';

if (file_exists($directory . $filename)) {
    // Handle the case where the file already exists
    // For example, rename the new file or prompt the user
} else {
    // Write the new file to the directory
    file_put_contents($directory . $filename, 'Hello, World!');
}