Messaging Mishap with GCM

Here is a demo of GCM that works:

If you refresh the page, you will notice a new random number. Only 25% of page refreshes actually send a message to GCM. Is this behavior normal or can I make some tweaks to the code to improve it?

The page does not have caching enabled.

Code:

<?php


require_once '../include/DB_Functions.php';


// Establish database connection
$db = new DB_Functions();

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

// API key for GCM
$apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

$result;

// Array to store phone registrations connected to this service
$registrationIDs = array();


$randomNum=rand(10,100);


echo "This is updateusers".$randomNum;
$_POST['message']="updateusers".$randomNum;
if (isset($_POST['message']) && $_POST['message'] != ''){   

echo "<br>if (isset) updateusers".$randomNum;
    // Message to be sent
    $id= ''.mysql_real_escape_string(htmlentities($_POST['server_id'])).'';
    $new_message= ''.mysql_real_escape_string(htmlentities($_POST['message'])).'';


    // Fetch client registration IDs
    $query ="SELECT * FROM GoogleCloudMsg";

    $queryresult=mysql_query($query);

    while($row=mysql_fetch_assoc($queryresult)){
    echo "<br>While loop updateusers".$randomNum;
        $regId=$row['GCMPhoneRegisteredId'];

        array_push($registrationIDs,$regId);

}



// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';

$fields;

if(!$id || $id==""){

    $fields = 
array(
'registration_ids' => $registrationIDs, 
'data' => array("message" => $new_message), 
'delay_while_idle'=> false,
'collapse_key'=>"".$randomNum.""
);

    echo "<br> id is blank updateusers".$randomNum;

}else{

$fields = 
array(
'registration_ids' => $registrationIDs, 
'data' => array("message" =>$new_message,"server_id"=>$id), 
 'delay_while_idle' => 'false',
'collapse_key'=>"".$randomNum.""
);

echo "<br>id exists updateusers".$randomNum;

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

// Open connection
$ch = curl_init();

// Set the URL, number of POST vars, POST data
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 ) );

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//     curl_setopt($ch, CURLOPT_POST, true);
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

// Execute the POST request
$result = curl_exec($ch);

// Close the connection
curl_close($ch);
echo $result;

}

echo "<br>mysql close updateusers".$randomNum;
 mysql_close();


?>

Answer №1

To address this issue, there were two possible solutions:

  1. Create and deploy a CA certificate.

  2. Use the command curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

This would result in the host not being verified.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on displaying the AJAX response in CakePHP 3.1

I'm working with a table that contains checkboxes. After selecting them, I want to calculate the sum of values from the table in a modal before confirming the form submission. Can someone guide me on how to render the AJAX response from the controller ...

Unable to output the string using htmlspecialchars

Oops! I made a mistake... just came across a JavaScript alert box! I just included htmlspecialchars. $src = './imgs/flag.jpg'; echo sprintf("<img alt=\"'.htmlspecialchars($name).'\" src=\"%s\" />", $src); I ...

Tips for accessing video links using video IDs from my personal Vimeo account

I'm currently using a Vimeo PRO account with a collection of videos, and my goal is to utilize PHP to fetch the direct link to a video (specifically the mp4 file URL that can be obtained in Vimeo's settings) by supplying the video ID. Despite ha ...

Failure to read the response will cause the HttpUrlConnection request to malfunction

I have been attempting to send a json request using HttpUrlConnection in Java. Despite following multiple examples, I am unable to successfully add data to the server as there is no response. Below is the code I am currently using: URL url = new URL(u ...

Is it possible to establish GEO filters for distance searches utilizing Yii2-Sphinx?

I've been having success with the Yii2-sphinx extension, but now I'm looking to implement distance search using sphinx. Specifically, I need to set latitude and longitude filters for a given postcode on my index. How can I go about setting up the ...

Access-Control-Allow-Origin causing a one-of-a-kind session problem

When trying to access data using cross-domain requests from multiple domains, I have included the following code in a PHP file at the backend: header("Access-Control-Allow-Origin: *"); Each time a new session is created for every request, resulting in a ...

managing website pages with a PHP curl script following authentication

I'm having trouble posting values to a field and completing the necessary steps to download a file. Can anyone provide insight into where I might be making a mistake? extract($_POST); $url=header("Location: http://gis.lntecc.com/bwssblnt/ ...

Submitting data through a PHP server-side script

I am facing a dilemma regarding why the form is not submitting and directing me to the index.php page. Being new to PHP, I am attempting to utilize the User object. Below is my current progress: <main> <header> <h1>Cr ...

Ways to showcase a response in a subsequent activity

Currently, I'm developing a search module in my application. I previously asked for guidance on how to display JSON response in another activity (reference). I have successfully sent a request to the server and received a response containing some dat ...

What is the best way to handle a JSON array within a Spinner?

I am currently facing a challenge with parsing a JSON file. I have the JSON file, but I am unsure of how to proceed with the parsing process. The structure of my JSON file is as follows: [ {"city":"Taipei", "area":["Songshan","Sinyi","Datong"]}, {"ci ...

Guide on how to showcase boxes or images as they are loaded using the jQuery media boxes library

I recently incorporated the Jquery mediabox () to showcase my image gallery. While it works well for a small number of images, it seems to wait until all images have loaded before displaying them when dealing with thousands of pictures. This delay can be ...

Best practices for setting the php max_execution_time

Attempting to adjust the execution time in php, but it doesn't seem to be functioning as expected. I have experimented with this solution. <?php function secondsToTime($s) { $h = floor($s / 3600); $s -= $h * 3600; $m = floor($s / 60) ...

problem with relational databases

Establishing a relationship between two tables (login_pre, privilege) looks like this: In the privilege table: +----------------------------------+ | AccessLevel | login_id | pre_id| |----------------------------------| | 1 | 1 | 1 ...

What steps can I take to prevent inserting an href into a conflicting keyword within a string?

Reviewing the code snippet provided: $text = "Google has released a version specifically for smart devices running Android operating system from version '25' of its famous Chrome browser. Google has not updated the Chrome application for Android ...

"Exploring the interactive features of a dual-axis line and column Highchart, focusing on dynamic percentage drill

In our current project, we are customizing graphs to meet a specific client requirement. The majority of the graphs we are working on involve a combination of line and column charts. Each graph requires a dropdown with a minimum of two levels, sometimes ex ...

The variables do not align with the number of parameters specified in the prepared statement

As I work on developing an application, I encounter an issue with the login page where I need to verify if a user exists in the database. Although my code seems correct as I only check for the name, I am facing an error when implementing the prepared state ...

Generating a JSON array in PHP and decoding it in an Android app has encountered an error: org.json.JSONException is throwing an exception stating

I have been using the following PHP code to generate a JSON array: $jsonData = array(); $jsonTempData = array(); $count=0; $result = $link->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result-& ...

Discover the logged-in user's email address utilizing LDAP/PHP

Is it possible to extract the user's email address from PHP after successful authentication using AuthLDAPURL in the htaccess file? ...

Upload file to database and move to new location

In order to gain a clearer understanding, I have a question regarding inserting data from a form. Let's say I have the following form: <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <inp ...

API does not support the grant type

I'm attempting to retrieve a token from the server response. It works perfectly fine using Postman, but when I try to debug it on Android, I encounter an error: unsupported_grant_type Below is my code snippet: HttpClient client = new DefaultHttpC ...