以前の記事でLINE Notifyとシェルスクリプトを使ってLINEにメッセージを送信する方法を説明しました。
今回の記事では、LINE NotifyとPHPを使ってLINEにメッセージを送信する方法を説明します。
結論
LINE NotifyとPHPを使ってLINEにメッセージを送信するPHPのソースは以下になります。
<?php
// LINEAPIの接続情報
define('LINE_API_URL' ,'https://notify-api.line.me/api/notify');
define('LINE_API_TOKEN','LINE NOTIFYで発行したアクセストークン');
function post_message($message){
// URL エンコードされたクエリ文字列を生成する
$data = http_build_query( [ 'message' => $message ]);
$options = [
'http'=> [
'method'=>'POST',
'header'=>'Authorization: Bearer ' . LINE_API_TOKEN . "\r\n"
. "Content-Type: application/x-www-form-urlencoded\r\n" ,
'content' => $data,
]
];
// ストリームコンテキストを作成する
$context = stream_context_create($options);
// POST送信
$resultJson = file_get_contents(LINE_API_URL, false, $context);
// レスポンス確認
$resultArray = json_decode($resultJson, true);
if($resultArray['status'] != 200) {
echo $resultArray['message'] . "\r\n";
return false;
}
return true;
}
// LINEで送りたいメッセージの内容
$message = 'テストメッセージ';
// LINEでメッセージ送信
post_message($message);
<?php
// LINEAPIの接続情報
define('LINE_API_URL' ,'https://notify-api.line.me/api/notify');
define('LINE_API_TOKEN','LINE NOTIFYで発行したアクセストークン');
function post_message($message){
// URL エンコードされたクエリ文字列を生成する
$data = http_build_query( [ 'message' => $message ]);
$options = [
'http'=> [
'method'=>'POST',
'header'=>'Authorization: Bearer ' . LINE_API_TOKEN . "\r\n"
. "Content-Type: application/x-www-form-urlencoded\r\n" ,
'content' => $data,
]
];
// ストリームコンテキストを作成する
$context = stream_context_create($options);
// POST送信
$resultJson = file_get_contents(LINE_API_URL, false, $context);
// レスポンス確認
$resultArray = json_decode($resultJson, true);
if($resultArray['status'] != 200) {
echo $resultArray['message'] . "\r\n";
return false;
}
return true;
}
// LINEで送りたいメッセージの内容
$message = 'テストメッセージ';
// LINEでメッセージ送信
post_message($message);
<?php
// LINEAPIの接続情報
define('LINE_API_URL' ,'https://notify-api.line.me/api/notify');
define('LINE_API_TOKEN','LINE NOTIFYで発行したアクセストークン');
function post_message($message){
// URL エンコードされたクエリ文字列を生成する
$data = http_build_query( [ 'message' => $message ]);
$options = [
'http'=> [
'method'=>'POST',
'header'=>'Authorization: Bearer ' . LINE_API_TOKEN . "\r\n"
. "Content-Type: application/x-www-form-urlencoded\r\n" ,
'content' => $data,
]
];
// ストリームコンテキストを作成する
$context = stream_context_create($options);
// POST送信
$resultJson = file_get_contents(LINE_API_URL, false, $context);
// レスポンス確認
$resultArray = json_decode($resultJson, true);
if($resultArray['status'] != 200) {
echo $resultArray['message'] . "\r\n";
return false;
}
return true;
}
// LINEで送りたいメッセージの内容
$message = 'テストメッセージ';
// LINEでメッセージ送信
post_message($message);
実行結果
上記のPHPファイルを実行するとLINEにメッセージが送信されます。