PHP security verification through Firebase Hosting
Overview:
Firebase Hosting is a static web page hosting service provided by Google that can conveniently host front-end applications. However, for websites that require dynamic processing, such as PHP websites that require user login and permission verification, Firebase Hosting alone cannot meet the needs. This article explains how to use PHP for secure authentication in Firebase Hosting, ensuring that only authenticated users can access sensitive data.
Steps:
firebase init functions
command. In the generated index.js
file, add the following code: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.authenticatedRequest = functions.https.onRequest((req, res) => { const key = req.query.key; if (key !== 'YOUR_SECRET_KEY') { return res.status(403).send('Forbidden'); } // 进行自定义的权限验证逻辑 // ... // 返回需要进行身份验证的数据 res.send('Authenticated data'); });
is used to implement verification logic. The following is a sample code:
<?php $key = "YOUR_SECRET_KEY"; $url = "https://us-central1-YOUR_PROJECT_ID.cloudfunctions.net/authenticatedRequest?key=".$key; // 如果请求带有 cookie,并且 cookie 中包含用户的身份信息 if(isset($_COOKIE['uid'])) { // 验证用户身份,例如从数据库中查询用户信息 $uid = $_COOKIE['uid']; $result = // 验证逻辑 if ($result === true) { // 身份验证通过,发送 GET 请求获取数据 $data = file_get_contents($url); echo $data; exit; } } // 身份验证未通过,跳转到登录页面 header("Location: login.php");
configuration file of Firebase Hosting, add the following configuration:
{ "hosting": { "rewrites": [ { "source": "**", "function": "authenticatedRequest" } ] } }
command on the terminal to deploy the PHP file to Firebase Hosting. Then, visit the website hosted by Firebase Hosting to see if PHP security verification was successfully implemented.
Through the above steps, we successfully implemented PHP security verification in Firebase Hosting. In Firebase Cloud Functions, we set up a function that only accepts a specific key to handle requests that require authentication. Then, in the PHP file, we authenticate the user, send a GET request to Firebase Cloud Functions to get the data, and redirect the unauthenticated user. This way, we can implement a secure PHP website and ensure that only authenticated users can access sensitive data.
The above is the detailed content of PHP Security Authentication with Firebase Hosting. For more information, please follow other related articles on the PHP Chinese website!