You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHP+MySQL实现Firebase批量推送通知?重复推送问题排查

问题原因及修复方案

问题根源

  1. 仅推送首个Token:mysqli_fetch_array($query)仅执行一次,只会从查询结果中取出第一条记录,导致仅能推送给第一个设备。
  2. 重复推送两次:mysqli_fetch_array()默认返回索引数组+关联数组的混合结果,遍历该数组时同一个Token会被重复添加到$registrationIds中,触发FCM重复推送。

修复步骤

  • 用循环遍历所有查询结果,替换单次的mysqli_fetch_array调用,确保获取数据库中所有Token。
  • 使用mysqli_fetch_assoc()(仅返回关联数组)避免混合数组带来的重复值问题。

修正后的完整代码

<form method="post" action="send_notification.php">
Title<input type="text" name="title">
Message<input type="text" name="message">
<!--Icon path<input type="text" name="icon">-->
Token<input type="text" name="token">
<input type="submit" name="submit" value="Send notification">
</form>

<?php
function sendNotification(){
    include("../config/con.php");
    $query = mysqli_query($conn,"SELECT token FROM devices");
    $registrationIds = [];

    // 遍历所有查询结果,提取唯一的token值
    while ($row = mysqli_fetch_assoc($query)) {
        $registrationIds[] = $row['token'];
    }

    $url ="https://fcm.googleapis.com/fcm/send";

    $fields=array(
        "registration_ids"=>$registrationIds,
        "notification"=>array(
            "body"=>$_REQUEST['message'],
            "title"=>$_REQUEST['title'],
            // "icon"=>$_REQUEST['icon'],
            "click_action"=>"https://google.com/"
        )
    );

    $headers=array(
        'Authorization: key=key',
        'Content-Type:application/json'
    );

    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_POST,true);
    curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode($fields));
    $result=curl_exec($ch);
    print_r($result);
    curl_close($ch);
}
if (isset($_POST['submit'])){
    sendNotification();
}
?>

额外说明

  • 确保../config/con.php中的数据库连接正常,且devices表的token字段存储有效FCM设备Token。
  • 若无需手动输入单个Token,可直接删除表单中的Token输入框。

内容的提问来源于stack exchange,提问作者Munajab

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 11:17:36