빨간색 부분은 사용자 환경에 맞게 조정





1. 폼작성 페이지

<html>

<head></head>

<body>

<div >

<h1>GCM 메세지 전송</h1>

<form method="post" action="./gcm_send.php/?push=true" >                                                      

<input type="hidden" name="push" value="true">

<textarea rows="5" name="message" cols="45" placeholder="메세지 입력"></textarea> <br/>

<input type="submit"  value=" 전송하기 " />

</form>

</div>

    

    </body>

</html>






2. GCM전송 페이지 : gcm_send.php


<?php



//디비연결

include $_SERVER['DOCUMENT_ROOT'] . "/db_connect.php";



//GCM전송 함수 

     function sendMessageThroughGCM($registatoin_ids, $message) {

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

        $fields = array(

            'registration_ids' => $registatoin_ids,

            'data' => $message,

        );


define("GOOGLE_API_KEY", "구글API키값");

        $headers = array(

            'Authorization: key=' . GOOGLE_API_KEY,

            'Content-Type: application/json'

        );

        $ch = curl_init();

        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_VERIFYHOST, 0);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);

        if ($result === FALSE) {

            die('Curl failed: ' . curl_error($ch));

        }

        curl_close($ch);

        return $result;

    }




//GCM메시지 전송

if(!empty($_POST["push"])) {

$pushMessage = $_POST["message"];

$pushMessage = urlencode($pushMessage);





//DB에서 전송할 기기아이디 조회

$reg_ids = array();

$sql = "SELECT and_reg_id FROM GCM_PUSH ";

$result = mysql_query($sql);

while($data = mysql_fetch_array($result)){

array_push($reg_ids, $data['and_reg_id']); 

}



$title = "GCM 알림!";

$title = urlencode($title);







  //JSON형태로 보냄 : 메세지 본문은 $pushMessage, 기타 값들을 추가해서 보낼 수 있다.

if (isset($reg_ids) && isset($pushMessage)) {

$message = array(

"ellord" => $pushMessage,

"extra" => $title


);

$pushStatus = sendMessageThroughGCM($reg_ids, $message);

}

}


?>



3. 기기에서 확인



끝.






블로그 이미지

엘로드넷

,