如何将Firebase谷歌登录信息存入自建服务器外部数据库?
How to Store Firebase Google Auth Data in Your Self-Hosted Database
Hey there! Let's break this down step by step since you're familiar with PHP for form submissions—this isn't as tricky as it sounds once you know the basics.
What Firebase Auth Data Should You Store?
Focus on stable, non-sensitive identifiers that let you reliably link Firebase users to your own database records:
uid: This is Firebase's unique, permanent ID for every user. It never changes (even if the user updates their email), so it’s perfect as the primary key in your database.- User email: Useful for communication or displaying user info. Firebase ensures emails are unique, but you can add a unique constraint in your database for extra safety.
- Optional extras: If your app needs user profiles, store
displayName(the user’s full name from Google) andphotoURL(their Google profile picture link). - Never store Firebase ID tokens or refresh tokens—these are temporary, sensitive credentials that shouldn’t live in your own database.
Where to Write the Storage Code
Since you’re comfortable with PHP, the best approach is a frontend-to-backend flow:
- Frontend (JavaScript): After the user logs in with Firebase, grab their auth data and send it to your PHP endpoint.
- Backend (PHP): Receive the data, validate it, and insert/update it in your self-hosted database.
Example Code Snippets
Frontend JavaScript (Firebase Login + Data Send)
Once the user successfully signs in with Google, extract their data and send it to your PHP script:
// Initialize Firebase first (you should already have this set up) firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider()) .then((result) => { const user = result.user; // Package the data we want to store const userData = { uid: user.uid, email: user.email, displayName: user.displayName, photoURL: user.photoURL }; // Send to your PHP endpoint fetch('/save-firebase-user.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(userData), }) .then(response => response.json()) .then(data => { console.log('User saved to your database:', data); }) .catch((error) => { console.error('Failed to save user:', error); }); }).catch((error) => { console.error('Login failed:', error); });
Backend PHP (Save User to Your Database)
Create a PHP script (e.g., save-firebase-user.php) to handle the incoming data. This uses PDO for secure database interactions:
<?php // Allow cross-origin requests if your frontend is on a different domain header("Access-Control-Allow-Origin: *"); header("Content-Type: application/json; charset=UTF-8"); // Get the data sent from the frontend $inputData = json_decode(file_get_contents("php://input")); // Validate required fields (uid and email are mandatory) if (!isset($inputData->uid) || !isset($inputData->email)) { echo json_encode(["error" => "Missing required user data"]); exit; } // Database connection details (use environment variables in production!) $dbHost = 'your-database-host'; $dbName = 'your-database-name'; $dbUser = 'your-database-username'; $dbPass = 'your-database-password'; try { // Connect to the database $pdo = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Check if the user already exists to avoid duplicates $checkQuery = $pdo->prepare("SELECT uid FROM users WHERE uid = :uid"); $checkQuery->bindParam(':uid', $inputData->uid); $checkQuery->execute(); if ($checkQuery->rowCount() === 0) { // Insert new user $insertQuery = $pdo->prepare(" INSERT INTO users (uid, email, display_name, photo_url) VALUES (:uid, :email, :displayName, :photoURL) "); $insertQuery->bindParam(':uid', $inputData->uid); $insertQuery->bindParam(':email', $inputData->email); $insertQuery->bindParam(':displayName', $inputData->displayName); $insertQuery->bindParam(':photoURL', $inputData->photoURL); $insertQuery->execute(); echo json_encode(["message" => "User successfully saved"]); } else { // User already exists—you could optionally update their data here echo json_encode(["message" => "User already exists in your database"]); } } catch(PDOException $e) { echo json_encode(["error" => "Database error: " . $e->getMessage()]); } // Clean up the connection $pdo = null; ?>
Key Tips for Safety & Reliability
- Validate everything: Always check that the data coming from the frontend is complete and valid (like the
uidandemailin the PHP example). - Secure your database: Don’t hardcode database credentials—use environment variables or a config file outside your web root.
- Idempotent requests: The check for existing users ensures you don’t create duplicate records if the user logs in multiple times.
内容的提问来源于stack exchange,提问作者user7939273
相关产品推荐
相关产品推荐

