phpmysqlfirebase-cloud-messaging

How to send push notifications to the device token stored in my mysql database


if I write them manually it works, it sends the notification to both devices.

/* 
$device_tokens = [
    "cpePj7mud-BKYh6hCZ1eDV:APA91bEPQAD0mLitP2CHX6WSLiewqRmtaqDu5WS6Nz_pfmATNCsIhits1vKHRj-L3rLluHua_IH4FIVJ2GwQ--------OnMXZFRbw3CrCLouawTBjU4iHFOxJ7bS9l_A1f",
    "fptsP-EwSb2R9FErVIo4Zk:APA91bEa6dGYkOZuF4gvXbJ_3ZjrwlYk8a1p1Fw2PgnCGCOVLgQaR23CcTyVacPh2ag1l9zdBnKXIOJ31fZdbhOByNLEZdqqb04wcxnJB---------b08wqfKUX44qe6RAbL7vn"
];
*/

$sql="SELECT token FROM tokens";                
$result=mysqli_query($conexion,$sql);               
    
while($device_token = mysqli_fetch_assoc($result)){
      $device_tokens[] = $device_token['token'];                    
    } 

foreach ($device_tokens as $token) {
    $response = sendFCMNotification($access_token, $token); 
    echo $response . '<br>';
}

but if I try to do it automatically from the database, it does not send them. In the database I use general utf8 ci If I print the token on the screen, I don't see the problem, it is exactly the same as if I type it in manually

So I save it. Does anyone know what the problem might be?

$token = $_POST['token'];
$id = $_SESSION['user_id'];

$sql="INSERT into tokens (id_jugador, token) values ('$id', '$token')";
echo $result=mysqli_query($conexion,$sql);

print_r() ->Array ( [token] => cpePj7mud-BKYh6hCZ1eDV:APA91bEPQAD0mLitP2CHX6WSLiewqRmtaqDu5WS6Nz_pfmATNCsIhits1vKHRj-L3rLluHua_IH4FIVJ2GwQ--------OnMXZFRbw3CrCLouawTBjU4iHFOxJ7bS9l_A1f ) Array ( [token] => fptsP-EwSb2R9FErVIo4Zk:APA91bEa6dGYkOZuF4gvXbJ_3ZjrwlYk8a1p1Fw2PgnCGCOVLgQaR23CcTyVacPh2ag1l9zdBnKXIOJ31fZdbhOByNLEZdqqb04wcxnJB---------b08wqfKUX44qe6RAbL7vn )


Solution

  • You can try to clean them prior to use them, since they work if you hardcoding them the problem might be how they're retrieved from the database, sometimes using print_r() to debug isn't the best way to actually see if there are missing or invisible characters:

    while($device_token = mysqli_fetch_assoc($result)){
        $token = trim($device_token['token']); // clean the token
        $token = utf8_encode($token);
    
        $device_tokens[] = $token;                    
    } 
    

    to debug $result or other variables in order to have better knowledge about what's happening, I'll recommend that you save this function somewhere you can use it globally:

    function debug($var) : string {
        echo '<pre>';
        var_dump($var);
        echo '</pre>';
        exit;
    }
    

    you'll have actually formatted code you can check for or simply use var_dump() to your $result