What are some best practices for handling file deletion and manipulation in PHP to avoid accidental data loss?

Accidental data loss can be prevented by implementing proper checks before deleting or manipulating files in PHP. One best practice is to always verify the file exists before attempting any deletion or modification operations. Additionally, consider using file locking mechanisms to prevent concurrent access and potential data corruption.

// Check if file exists before deleting
$file = 'example.txt';
if (file_exists($file)) {
    unlink($file);
    echo 'File deleted successfully';
} else {
    echo 'File does not exist';
}

// Use file locking to prevent concurrent access
$handle = fopen('example.txt', 'r+');
if (flock($handle, LOCK_EX)) {
    // Perform file manipulation operations
    flock($handle, LOCK_UN);
} else {
    echo 'Could not lock the file';
}
fclose($handle);