日本気象協会 (tenki.jp)のホームページから天気図と雨雲レーダーのデータを取得して、自分のサイトに表示するようにしているが、先週から突然、以下のエラーメッセージがでてデータ取得ができなくなった。
数か月前、tenki.jpのサイトはサイバー攻撃でアクセスできない問題が発生したので、その対策としてtenki.jpサイトでBasic認証を要求する仕様に変更したきらいがある。そこで、下記のサイト記事を参考に、file_get_contentsにユーザーエージェントやリファラを設定した。
参考記事:【PHP】file_get_contentsにユーザーエージェントやリファラを設定
修正プログラム:
/wp-content/themes/cocoon-child-master/tenkizu-scrape.php
/wp-content/themes/cocoon-child-master/satellite-scrape.php
<tenkizu-scrape.php 修正例>
Before :
// 取得したいwebサイトを読み込み
// tenkizu ///////////////////////////////////////////////////////////
$html = file_get_contents("https://tenki.jp/guide/chart/");
After:
//コンテンツ取得先
$url = "https://tenki.jp/guide/chart/";
//ヘッダーの設定
$header = array(
"Content-Type: application/x-www-form-urlencoded",
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0",
"Referer: https://home-atmo.com"
);
//オプション設定
$options =array(
'http' =>array(
'method' => "GET",
'header' => implode("\r\n", $header),
)
);
//コンテンツ取得
$html = file_get_contents($url, false, stream_context_create($options));
その結果、エラーは無事解消された。
修正コードを検証する余裕がないので、とりあえずネット記事丸呑みで暫定対策を備忘録的に記録しておく。
コメント