<?
$conexion = mysqli_connect("localhost", "database_user", "database_password", "database_name");
$idRegistro = $_POST['idregistro'];
$mensajeEnvio = $_POST['mensaje'];
$GoogleApiKey = "RIadGGw4TTgfeer.......jjeeAS5YYgjddmqQp98";
$otroDatoEnvio = "hola mundo";
mysqli_set_charset($conexion, "utf8");
if (mysqli_connect_errno()) {
    printf("Conexión fallida: %s\n", mysqli_connect_error());
    mysqli_close($conexion);
    exit;
} else {
    $sql = "SELECT * FROM c2dm WHERE idregistro ='".$_POST['idregistro']."'";
    $resultado = mysqli_query($conexion,$sql);
    if ($resultado) {
        $numeroRegistros=mysqli_num_rows($resultado);
        if ($numeroRegistros == 1) {
                $resultadoGCM = enviarMensajeGCM($idRegistro,$mensajeEnvio, $otroDatoEnvio, $GoogleApiKey);
        } else {
                echo 'error';
        }
    }  
}
mysqli_close($conexion);
function enviarMensajeGCM($GCMregid, $mensaje, $otrodato, $apiKey){
    $GCMapiKey = $apiKey;
 
    // Registro Id del dispositivo
    $registrationIDs = $GCMregid;
 
    // Se establecen las variables que se van a mandar por POST
    $cty="Content-Type: application/json";
 
    // URL para el envio de los mensajes
    //$url = 'https://android.googleapis.com/gcm/send';   //Antigua URL
    $url = 'https://gcm-http.googleapis.com/gcm/send';
 
    $fields = array(
    'data' => array( "mensaje" => $mensaje , "otrodato" => $otrodato),
    'to'   => $registrationIDs
    );
 
    $headers = array(
    'Authorization: key=' . $apiKey,
    'Content-Type: application/json'
    );
 
 
    // Abre una conexión
    $ch = curl_init();
 
    // Establece el url, numero de variables Post y los datos del mensaje
 
    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_SSL_VERIFYPEER, false);
    curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );
 
    // Ejecuta el post
    $res_GCM_funcion = curl_exec($ch);
     
    if ($res_GCM_funcion === FALSE) {
        die('Curl failed: ' . curl_error($ch));
    }
 
    // Cierra la conexión
    curl_close($ch);
 
    //decodifica en el array $res la cadena Json que devuelve Google
    $res = json_decode($res_GCM_funcion,true);
    echo 'Google responde: ';
    echo '<br>multicast_id: ';
    echo $res['multicast_id'];
    echo '<br>success: ';
    echo $res['success'];
    echo '<br>failure: ';
    echo $res['failure'];
    echo '<br>canonical_ids: ';
    echo $res['canonical_ids'];
    echo '<br>success: ';
    echo $res['success'];
    echo '<br>message_id: ';
    echo $res['results'][0]['message_id'];
    echo '<br>registration_id: ';
    echo $res['results'][0]['registration_id'];
    echo '<br>error: ';
    echo $res['results'][0]['error'];
 
 
    //Devuelve el array
    return $res;
 
}
?>