概要説明
SSL証明証が適切ではないサイトのデータをfile_get_contents()で取得した際に発生したエラーの対応。サーバー側での対応が必要な場合もありますが、証明書の有効性をチェックしないという条件を指定することで回避できる場合があります。
~ 目次 ~
エラーログ
Warning: file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:error:xxxxx:SSL routines:ssl3_get_server_certificate:certificate verify failed in
Warning: file_get_contents(): Failed to enable crypto in
Warning: file_get_contents(https://xxxxxx): failed to open stream: operation failed in
PHPの記述を変更
$context = stream_context_create([
    'ssl' => [
        'verify_peer'      => FALSE,
        'verify_peer_name' => FALSE
    ]
]);
$get_html = file_get_contents($target_url, FALSE, $context);
    事前にエラーになる可能性があると判断できる場合は「@」(アットマーク)をつける
@file_get_contents($target_url, FALSE, $context);
これでエラーを出力しなくなります。
補足:ステータスコードが知りたい場合 ( ページの存在確認など )
// 先頭から1024byteだけ読み込み
@file_get_contents($target_url, FALSE, NULL, 0, 1024);
// レスポンスヘッダーから通信内容を確認
$status_code = explode(' ', $http_response_header[0]);
if ( $status_code['1'] == '200' ) {
    // 正常に取得できた場合の処理
}
    


