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.
$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!');
}
Related questions
-
opendir folder access PHP
-
mail function PHP SMTP
-
PHP multi-step deletion process security