Wednesday, April 11, 2012

Parse: Sending Push Notifications using PHP with/without cURL

I started using Parse to easily send push notifications to phones with my app. However I needed to use PHP to send the notifications and not from the command line as shown in their api.

I came up with the following using cURL:

 $ch = curl_init(); 

 $arr = array();
 array_push($arr, "X-Parse-Application-Id: YOUR_APPLICATION_ID");
 array_push($arr, "X-Parse-REST-API-Key: YOUR_REST_API_KEY");
 array_push($arr, "Content-Type: application/json");
 curl_setopt($ch, CURLOPT_HTTPHEADER, $arr);
 curl_setopt($ch, CURLOPT_URL, '');
 curl_setopt($ch, CURLOPT_POST, true);
 curl_setopt($ch, CURLOPT_POSTFIELDS, '{ "channel": "","data": { "alert": "Red Sox win 7-0!" } }');

And if for some reason you don't want to use cURL, here is the code using the default stream_context_create and file_get_contents methods:

 $url = '';
 $data = '{"channel":"","data":{ "alert":"Red Sox win 7-0!"}}';

 $opts = array('http' =>
   'method'  => 'POST',
   'header'  => "X-Parse-Application-Id: YOUR_APPLICATION_ID\r\n
       X-Parse-REST-API-Key: YOUR_REST_API_KEY\r\n
       Content-Type: application/json\r\n
       Content-Length: " . strlen($data) . "\r\n",
   'content' => $data

 $context  = stream_context_create($opts); 
 $result = file_get_contents($url, false, $context);
 echo $result;


  1. none of the above methods are working

  2. working, to prevent result from sending header add the following line after curl_init(); this prevents header already sent error

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);