PHPのfile_get_contentで他サイトのコンテンツ取得時に403エラーがでることがあります。
エラー内容
次のようにfile_get_contentで他サイトのコンテンツを取得しようとすると403エラーがでます。
- ちなみに私はServerFaultのサイト(
https://serverfault.com/)や、StuckOverFlowのページを引用するためにfile_get_contentを使うときにこのエラーが出ました。 
他サイトのページを取得するPHPプログラム
<?php
$url = 'https://serverfault.com/xxxx';
$html = file_get_contents($url);
環境
- PHP 8.0.11
 
原因
file_get_contentはデフォルトでuser_agentが設定されていません。そのため、サーバー側(今回はServerFault)からは不正アクセスと判断されてしまい、403エラーが出てしまいます。
解決方法
file_get_contentのオプションで user_agentを設定することで解決 します。
修正したPHPプログラム
<?php
$url = 'https://serverfault.com/xxxx';
$options = [
    'http' => [
        'method' => 'GET',
        'header' => 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.54 Safari/537.36',
    ],
];
$context = stream_context_create($options);
$html = file_get_contents($url, false, $context);
参考
https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q11227164386