Warning: file_get_contents(): SSL operation failed with codeの対応

概要説明

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' ) {
    // 正常に取得できた場合の処理
}

関連機能

  1. サイトマップエラー error on line 2 at column 6: XML declaration allowed only at the start of the document の修正…

  2. WordPressページで404 not foundの場合にトップページにリダイレクトを行う

  3. WordPress SiteGuard プラグインにて入力を間違えて管理者アカウントがログインロック状態になった場合の解除方法

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

理想を語れなくなったら
人間の進化は止まるぞ

鋼の錬金術師
by ロイ・マスタング

Profile

PAGE TOP