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

  2. Notice: ob_end_flush(): failed to delete and flush buffer. No buffer to delete or flush inの対応

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

サイドバー

よく使うカスタマイズ

最近の記事

アニメの名言集

疑って後悔するよりは
信じて後悔しようぜ!

ソードアート・オンライン
by キリト

Profile

PAGE TOP
Amazon プライム対象