I’m using this firestore client that doesnt require GRPC and it is made by bensontrent
GITHUB REPO: https://github.com/bensontrent/firestore-php
The problem I have is that my index.php is not working and I think I initialized the firebase client correctly, I am logging the errors in a file but there is no error showing up in the file and I get this errors only in the website when i load it.
HTTP ERROR 500
This page isn’t working
e-barter.x10.bz is currently unable to handle this request.
I tried initializing the firebase like this, just how the repo documentation said:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error_log.txt'); // Log errors to a file
// Database connection
require 'db_connect.php';
require '../vendor/autoload.php';
use bensontrentfirestore-phpFirestoreClient;
// Initialize variables with default values
$topRanked = $topRated = $topPosters = [];
$totalUsers = $totalItems = 0;
$recentItems = [];
try {
// Initialize Firestore client
$firestore = new FirestoreClient(
'ebarter-f3229',
'AIzaSyB2rf5zxpvwUc7U8UZZ3TqujAycg62av8Q', (here in the API key, I'm not sure if its the firebase webapi key or i need to generate another key in the google cloud???)
['database' => '(default)']
);
this is the queries i’m trying to do:
// Function to calculate user rankings
function calculateUserRankings($firestore) {
$userStats = [];
try {
// Get all users
$users = $firestore->listDocuments('users');
foreach ($users as $userDoc) {
$userId = $userDoc->id();
$userData = $userDoc->data();
$userStats[$userId] = [
'fullName' => $userData['fullName'] ?? 'Anonymous',
'postedItemsCount' => 0,
'completedTradesCount' => 0,
'totalRatings' => 0,
'sumRatings' => 0,
'averageRating' => 0,
'totalScore' => 0
];
}
// Get items
$items = $firestore->listDocuments('items');
foreach ($items as $item) {
$itemData = $item->data();
$userId = $itemData['userId'] ?? '';
if ($userId && isset($userStats[$userId])) {
$userStats[$userId]['postedItemsCount']++;
}
}
// Get completed trades
$completedTrades = $firestore->query('barterOffers')
->where('status', '=', 'completed')
->get();
foreach ($completedTrades as $trade) {
$tradeData = $trade->data();
$itemOwnerId = $tradeData['itemOwnerId'] ?? '';
$likerId = $tradeData['likerId'] ?? '';
if ($itemOwnerId && isset($userStats[$itemOwnerId])) {
$userStats[$itemOwnerId]['completedTradesCount']++;
}
if ($likerId && isset($userStats[$likerId])) {
$userStats[$likerId]['completedTradesCount']++;
}
}
// Get ratings
$ratings = $firestore->listDocuments('ratings');
foreach ($ratings as $rating) {
$ratingData = $rating->data();
$ratedUserId = $ratingData['ratedUserId'] ?? '';
$ratingValue = $ratingData['rating'] ?? 0;
if ($ratedUserId && isset($userStats[$ratedUserId])) {
$userStats[$ratedUserId]['totalRatings']++;
$userStats[$ratedUserId]['sumRatings'] += $ratingValue;
}
}
// Calculate scores
foreach ($userStats as $userId => &$stats) {
if ($stats['totalRatings'] > 0) {
$stats['averageRating'] = $stats['sumRatings'] / $stats['totalRatings'];
}
$ratingScore = $stats['averageRating'] * 2 * $stats['totalRatings'];
$tradesBonus = min($stats['completedTradesCount'], 10);
$itemsBonus = min($stats['postedItemsCount'] * 0.5, 10);
$stats['totalScore'] = (int) round($ratingScore + $tradesBonus + $itemsBonus);
}
// Sort and return results
$topRanked = $userStats;
usort($topRanked, fn($a, $b) => $b['totalScore'] <=> $a['totalScore']);
$topRated = $userStats;
usort($topRated, fn($a, $b) =>
$b['averageRating'] <=> $a['averageRating'] ?:
$b['totalRatings'] <=> $a['totalRatings']);
$topPosters = $userStats;
usort($topPosters, fn($a, $b) => $b['postedItemsCount'] <=> $a['postedItemsCount']);
return [
'topRanked' => array_slice($topRanked, 0, 5),
'topRated' => array_slice($topRated, 0, 5),
'topPosters' => array_slice($topPosters, 0, 5)
];
} catch (Exception $e) {
error_log("Firestore Query Error: " . $e->getMessage());
return ['topRanked' => [], 'topRated' => [], 'topPosters' => []];
}
}
// Get rankings
$rankings = calculateUserRankings($firestore);
$topRanked = $rankings['topRanked'];
$topRated = $rankings['topRated'];
$topPosters = $rankings['topPosters'];
} catch (Exception $e) {
error_log("Firestore Init Error: " . $e->getMessage());
}
// Get database counts (this is from my domain's database and not part of firebase)
try {
$userCountResult = $conn->query("SELECT COUNT(*) as total_users FROM users");
$totalUsers = $userCountResult ? $userCountResult->fetch_assoc()['total_users'] : 0;
$itemCountResult = $conn->query("SELECT COUNT(*) as total_items FROM items");
$totalItems = $itemCountResult ? $itemCountResult->fetch_assoc()['total_items'] : 0;
$itemsResult = $conn->query("SELECT i.*, u.username, u.city FROM items i JOIN users u ON i.userId = u.userId ORDER BY i.created_at DESC LIMIT 12");
$recentItems = $itemsResult ? $itemsResult->fetch_all(MYSQLI_ASSOC) : [];
} catch (Exception $e) {
error_log("MAIN ERROR: " . $e->getMessage());
// Display user-friendly error message
die("<div class='alert alert-danger'>An error occurred while loading the page. Please try again later. Technical details have been logged.</div>");
}
?>