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. Fatal error: Uncaught Error: Call to undefined function create_function()の対応

  3. WP Mail SMTP プラグインのDMARC警告対応について ( エックスサーバー )

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

その人を知りたければ、
その人が何に対して怒りを感じるかを知れ

HUNTER×HUNTER
by ミト

Profile

PAGE TOP
Amazon プライム対象