How can file_exists() function be used to check for existing usernames in PHP registration forms?
When creating a registration form in PHP, you can use the file_exists() function to check if a username already exists in a file or database before allowing a user to register with that username. This helps prevent duplicate usernames and ensures the uniqueness of each user's account.
$username = $_POST['username'];
if (file_exists('usernames.txt')) {
$usernames = file('usernames.txt', FILE_IGNORE_NEW_LINES);
if (in_array($username, $usernames)) {
echo 'Username already exists. Please choose a different username.';
} else {
// Proceed with user registration
// Add the new username to the file or database
file_put_contents('usernames.txt', $username . PHP_EOL, FILE_APPEND);
echo 'Registration successful!';
}
} else {
// Create the file if it doesn't exist
file_put_contents('usernames.txt', $username . PHP_EOL);
echo 'Registration successful!';
}