411 - length required error while posting json data using PHP curl

1.7k Views Asked by At

I am trying to post json data to the GCM (Google Cloud Messaging) server using php curl. Below is my code snipppet

$url="https://android.googleapis.com/gcm/send";
$fields=array('registration_ids'=>$registration_ids,'data'=>$message);
$headers=array('Authorization:key='. GOOGLE_API_KEY,
               'Content-Type:application/json',
               'Content-Length: '.strlen(json_encode($fields)));
$ch=curl_init();
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch,CURLOPT_POSTFIELDS,json_encode(fields));
$result=curl_exec($ch);
curl_close($ch);
echo $result;

On running this script i get an error saying

Error 411(Length Required) !! 1

I searched several forums but not getting the solution for this. Can anyone help?

1

There are 1 best solutions below

0
On

Odd, I found the same PHP code but it didn't complain for me. Try this code here and paste it to http://phpfiddle.org/.

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'Axxxxxxxxxxxxxxxxxx' );


$registrationIds = array("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

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

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>