Hey there, fellow PHP enthusiasts! Ready to supercharge your app's authentication system? Look no further than Firebase Auth. It's like having a security guard for your app, but way cooler and less intimidating. In this guide, we'll walk through integrating Firebase Auth into your PHP application. Trust me, your future self will thank you for this level-up in user management.
Before we dive in, let's make sure we've got our ducks in a row:
Got all that? Great! Let's roll up our sleeves and get to work.
First things first, let's get the Firebase PHP SDK on board:
composer require kreait/firebase-php
Now, let's set up our Firebase credentials. Create a new PHP file (let's call it firebase-config.php
) and add this:
<?php require __DIR__.'/vendor/autoload.php'; use Kreait\Firebase\Factory; $factory = (new Factory) ->withServiceAccount('/path/to/your/serviceAccountKey.json') ->withDatabaseUri('https://your-project-id.firebaseio.com'); $auth = $factory->createAuth();
Replace the path and URI with your actual Firebase project details. Don't worry, it's not rocket science!
Let's start by adding new users to our Firebase family:
try { $userProperties = [ 'email' => '[email protected]', 'emailVerified' => false, 'password' => 'secretPassword', 'displayName' => 'John Doe', ]; $createdUser = $auth->createUser($userProperties); echo 'Successfully created new user: '.$createdUser->uid; } catch (\Kreait\Firebase\Exception\Auth\EmailExists $e) { echo 'Email already exists'; }
Time to roll out the welcome mat:
try { $signInResult = $auth->signInWithEmailAndPassword($email, $password); $user = $signInResult->data(); echo 'Welcome back, '.$user['displayName'].'!'; } catch (\Kreait\Firebase\Exception\Auth\InvalidPassword $e) { echo 'Invalid password'; }
Everyone forgets sometimes. Let's make it easy for them:
try { $auth->sendPasswordResetLink($email); echo 'Password reset email sent'; } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) { echo 'No user found with this email address'; }
People change, and so should their profiles:
try { $properties = [ 'displayName' => 'Jane Doe', 'photoUrl' => 'http://example.com/jane-doe.jpg', ]; $updatedUser = $auth->updateUser($uid, $properties); echo 'Successfully updated user'; } catch (\Kreait\Firebase\Exception\Auth\UserNotFound $e) { echo 'User not found'; }
Want to give some users superpowers? Custom claims to the rescue:
$auth->setCustomUserClaims($uid, ['admin' => true]); // Later, to verify: $token = $auth->verifyIdToken($idToken); $claims = $token->claims()->get('admin'); if ($claims === true) { echo 'User is an admin'; }
Let's lock down those endpoints:
function verifyToken($token) { global $auth; try { $verifiedIdToken = $auth->verifyIdToken($token); return $verifiedIdToken->claims()->get('sub'); } catch (\Exception $e) { return null; } } // Use it in your API $token = $_SERVER['HTTP_AUTHORIZATION'] ?? ''; $uid = verifyToken($token); if ($uid) { // Proceed with the API call } else { http_response_code(401); echo json_encode(['error' => 'Unauthorized']); exit; }
Always expect the unexpected:
Don't forget to test! Here's a quick example using PHPUnit:
public function testUserCreation() { $email = '[email protected]'; $password = 'testPassword123'; $user = $this->auth->createUser([ 'email' => $email, 'password' => $password, ]); $this->assertNotNull($user->uid); $this->assertEquals($email, $user->email); }
And there you have it! You've just leveled up your PHP app with Firebase Auth. Remember, this is just the beginning. Firebase offers a treasure trove of features waiting to be explored. So go forth, authenticate with confidence, and may your users always stay secure!
Happy coding, and don't forget to high-five yourself for making it this far. You've earned it! 🚀👨💻👩💻