In what scenarios would implementing OAuth be more suitable than creating a custom user authentication system in PHP?

Implementing OAuth would be more suitable than creating a custom user authentication system in PHP when you want to allow users to log in using their existing accounts from popular platforms like Google, Facebook, or Twitter. OAuth simplifies the authentication process by delegating the responsibility to the third-party provider, reducing the complexity and security risks of managing user credentials yourself.

// Example of implementing OAuth using Google Sign-In in PHP

// Start OAuth flow by redirecting user to Google's authentication URL
$googleAuthUrl = 'https://accounts.google.com/o/oauth2/auth?client_id=YOUR_CLIENT_ID&redirect_uri=YOUR_REDIRECT_URI&scope=email&response_type=code';
header('Location: ' . $googleAuthUrl);
exit;

// Handle the callback from Google after user authentication
if (isset($_GET['code'])) {
    $code = $_GET['code'];

    // Exchange the authorization code for an access token
    // Make a POST request to Google's token endpoint with the code and client credentials
    // Store the access token securely for future API calls
}